package main

import (
	"bytes"
	"encoding/json"
	"errors"
	"fmt"
	"gopkg.in/mgo.v2/bson"
	"io/ioutil"
	"net/http"
	"server/src/storage"
	"strconv"
	"strings"
	"time"

	"server/src/ac"
	"server/src/gps"
	"server/src/languageswitcher"
)

type HttpListener struct {
	dbo          *DBOperation
	cfg          *Config
	langSwitcher *languageswitcher.LanguageSwitcher
	_ac          *ac.Controller
}

func ListenHttpService(cfg *Config, db *DBOperation) {
	listenter := HttpListener{}
	listenter.dbo = db
	listenter.cfg = cfg
	listenter.langSwitcher = languageswitcher.NewLanguageSwitcher(db.session, db.dbName)

	acConfig := ac.Config{
		RedisUrl: cfg.Redis.Url,
		Expire:   cfg.Redis.Expire,
		Key:      cfg.Redis.Key,
	}
	_ac, _ := ac.New(&acConfig)

	listenter._ac = _ac

	zLog(nil, "开始监听Https端口:", cfg.HttpPort)
	listenter.listen(cfg.HttpPort)
}

func (p *HttpListener) listen(port int) {
	// 文件服务
	http.Handle("/", http.FileServer(http.Dir(storage.Storage.AbsPath)))
	//数据查询类
	//接收器最新状态
	http.HandleFunc("/data/laststatus", p.ReceiverLastStatus)
	//查询接收器历史轨迹
	http.HandleFunc("/data/track", p.ReceiverTrack)
	//查询传感器胎温胎压历史数据
	http.HandleFunc("/data/receivertiredatahistory", p.ReceiverTireDataHistory)
	//所有接收器的最新位置
	http.HandleFunc("/data/receivergps", p.ReceiverPositions)
	//查询传感器胎温胎压历史数据
	http.HandleFunc("/data/sensordatahistory", p.SensorDataHistory)
	//查询轮位胎温胎压历史数据
	http.HandleFunc("/data/sensordatahistory2", p.SensorDataHistory2)
	//根据传感器编码查询轮胎信息
	http.HandleFunc("/data/tireinfo", p.TireInfo)
	//接收器查询
	http.HandleFunc("/data/queryreceiverid", p.QueryReceiverId)
	//设备查询
	http.HandleFunc("/data/properties", p.Properties)

	//设备管理类
	//批量创建接收器
	http.HandleFunc("/receiver/batchcreate", p.ReceiverBatchCreate)
	//接收器列表(App端)
	// http.HandleFunc("/devices/receivers", p.Receivers)
	http.HandleFunc("/devices/receivers", p.ReceiversV2)
	//接收器列表(PC端)
	http.HandleFunc("/receiver/list", p.ReceiverList)
	//接收器列表(for大屏展示)
	http.HandleFunc("/receiver/view", p.ReceiverView)
	//接收器类别
	http.HandleFunc("/receiver/type", p.ReceiverType)
	//删除指定轮位的数据
	http.HandleFunc("/receiver/removesn", p.ReceiverRemoveSN)
	//更换接收器
	http.HandleFunc("/receiver/exchange", p.ReceiverExchange)
	//接收器作废
	http.HandleFunc("/receiver/invalid", p.ReceiverInvalid)
	//绑定传感器，下发对码
	http.HandleFunc("/receiver/bindsensor", p.ReceiverBindSensor)
	//查询高低压和高温阀值
	http.HandleFunc("/receiver/threshold", p.ReceiverThresholt)
	//设置高低压和高温阀值
	http.HandleFunc("/receiver/setthreshold", p.ReceiverSetThreshold)
	//查询数据上传频率
	http.HandleFunc("/receiver/frequncy", p.ReceiverUploadFrequncy)
	//设置设备上传数据的频率
	http.HandleFunc("/receiver/setfrequncy", p.ReceiverSetUploadFrequncy)
	//设置设备休眠
	http.HandleFunc("/receiver/setdevicesleep", p.ReceiverSetDeviceSleep)
	//接收器的传感器信息
	http.HandleFunc("/receiver/sensors", p.ReceiverSensors)
	//原始数据
	http.HandleFunc("/receiver/rawdata", p.ReceiverRawData)
	//接收器批量导入
	http.HandleFunc("/receiver/import", p.ReceiverImport)
	//修改设备类别
	http.HandleFunc("/receiver/changetype", p.ReceiverChangeType)
	//将接收器划归某公司
	http.HandleFunc("/receiver/settocompany", p.ReceiverSetToCompany)
	//将一组接收器从某公司或车队名下移除
	http.HandleFunc("/receiver/removefromcompany", p.ReceiverRemoveFromCompany)
	//接收器归属
	http.HandleFunc("/receiver/belong", p.ReceiverBelong)
	//清空传感器数据
	http.HandleFunc("/receiver/clean", p.ReceiverClean)
	//修改设备的服务器IP和端口
	http.HandleFunc("/receiver/setserver", p.ReceiverSetServer)
	//远程升级
	http.HandleFunc("/receiver/remoteupdate", p.ReceiverRemoteUpdate)
	//接收器详情
	http.HandleFunc("/receiver/detail", p.ReceiverDetail)
	//接收器最新位置
	http.HandleFunc("/receiver/location", p.ReceiverLocation)
	//轨迹日期查询
	http.HandleFunc("/receiver/trackdates", p.ReceiverTrackDates)
	//设置接收器的固定胎温胎压
	http.HandleFunc("/receiver/setfixtempandpres", p.ReceiverSetFixTempAndPres)
	//查询接收器的固定胎温胎压
	http.HandleFunc("/receiver/fixtempandpres", p.ReceiverFixTempAndPres)

	//公司管理
	//公司列表
	http.HandleFunc("/company/list", p.CompanyList)
	//添加公司
	http.HandleFunc("/company/add", p.CompanyAdd)
	//修改公司信息
	http.HandleFunc("/company/modify", p.CompanyModify)
	//删除公司
	http.HandleFunc("/company/delete", p.CompanyDelete)
	//公司概况
	http.HandleFunc("/company/brief", p.CompanyBrief)
	//子车队列表
	http.HandleFunc("/company/subteams", p.CompanySubTeam)

	//司机管理
	//司机姓名列表
	http.HandleFunc("/driver/namelist", p.DriverNameList)
	//司机列表
	http.HandleFunc("/driver/list", p.DriverList)
	//添加司机
	http.HandleFunc("/driver/add", p.DriverAdd)
	//修改司机
	http.HandleFunc("/driver/edit", p.DriverEdit)
	//删除司机
	http.HandleFunc("/driver/delete", p.DriverDelete)

	//车队管理
	//公司下属的车队
	http.HandleFunc("/team/list", p.TeamList)
	//添加车队
	http.HandleFunc("/team/add", p.TeamAdd)
	//编辑车队
	http.HandleFunc("/team/edit", p.TeamEdit)
	//删除车队
	http.HandleFunc("/team/delete", p.TeamDelete)

	//车辆管理
	//车辆品牌列表
	http.HandleFunc("/vehicle/brandlist", p.VehicleBrandList)
	//添加车辆品牌
	http.HandleFunc("/vehicle/brandadd", p.VehicleBrandAdd)
	//修改车辆品牌
	http.HandleFunc("/vehicle/brandedit", p.VehicleBrandEdit)
	//删除车辆品牌
	http.HandleFunc("/vehicle/brandremove", p.VehicleBrandDelete)
	//车辆型号列表
	http.HandleFunc("/vehicle/modellist", p.VehicleModelList)
	//添加车辆型号
	http.HandleFunc("/vehicle/modeladd", p.VehicleModelAdd)
	//修改车辆型号
	http.HandleFunc("/vehicle/modeledit", p.VehicleModelEdit)
	//删除车辆型号
	http.HandleFunc("/vehicle/modelremove", p.VehicleModelDelete)

	//车辆列表
	http.HandleFunc("/vehicle/list", p.VehicleList)
	http.HandleFunc("/vehicle/list2", p.VehicleList2)
	//添加车辆
	//http.HandleFunc("/vehicle/add", p.VehicleAdd)
	http.HandleFunc("/vehicle/add2", p.VehicleAdd2)
	//修改车辆
	//http.HandleFunc("/vehicle/edit", p.VehicleEdit)
	http.HandleFunc("/vehicle/edit2", p.VehicleEdit2)
	//删除车辆
	http.HandleFunc("/vehicle/remove", p.VehicleRemove)
	//车辆信息
	http.HandleFunc("/vehicle/info", p.VehicleInfo)
	//车辆轮胎信息
	http.HandleFunc("/vehicle/tires", p.VehicleTires)
	http.HandleFunc("/vehicle/tires/v2", p.VehicleTires_v2)
	//查询车辆某轮位上轮胎的信息
	http.HandleFunc("/vehicle/tire", p.VehicleTire_v2)

	//轮胎管理
	//轮胎品牌列表
	http.HandleFunc("/tire/brandlist", p.TireBrandList)
	//添加轮胎品牌
	http.HandleFunc("/tire/brandadd", p.TireBrandAdd)
	//修改轮胎品牌
	http.HandleFunc("/tire/brandedit", p.TireBrandEdit)
	//删除轮胎品牌
	http.HandleFunc("/tire/brandremove", p.TireBrandRemove)
	//轮胎型号列表
	http.HandleFunc("/tire/modellist", p.TireModelList)
	//轮胎型号数组
	http.HandleFunc("/tire/models", p.TireModels)
	//轮胎花纹数组
	http.HandleFunc("/tire/patterns", p.TirePatterns)
	//添加轮胎规格
	http.HandleFunc("/tire/modeladd", p.TireModelAdd)
	//轮胎规格信息
	http.HandleFunc("/tire/modelinfo", p.TireModelInfo)
	//修改轮胎规格
	http.HandleFunc("/tire/modeledit", p.TireModelEdit)
	//删除轮胎规格
	http.HandleFunc("/tire/modelremove", p.TireModelRemove)
	//设置轮胎信息
	http.HandleFunc("/tire/set", p.TireSet)
	//轮胎列表（老接口，逐渐取消）
	http.HandleFunc("/tire/list", p.TireList)
	//轮胎查询
	http.HandleFunc("/tire/query", p.TireQuery)
	//根据RFID查询轮胎号
	http.HandleFunc("/tire/tnobyrfid", p.TireByRFID)
	//添加轮胎
	http.HandleFunc("/tire/add", p.TireAdd)
	//修改轮胎
	http.HandleFunc("/tire/edit", p.TireEdit)
	//删除轮胎
	http.HandleFunc("/tire/delete", p.TireDelete)
	//设置胎纹深度报警的阀值
	http.HandleFunc("/tire/setthreshold", p.TireSetThreshold)
	//轮胎基本信息
	http.HandleFunc("/tire/baseinfo", p.TireBaseInfo)
	//轮胎生命周期
	http.HandleFunc("/tire/lifecircle", p.TireLifeCircle)
	//轮胎入库-米其林
	http.HandleFunc("/tire/mqlstockin", p.TireMqlStockIn)
	//轮胎下车
	http.HandleFunc("/tire/unload", p.TireUnload)
	//交换轮位
	http.HandleFunc("/tire/exchangeposition", p.TireExchangeTirePosition)
	//轮胎维修
	http.HandleFunc("/tire/maintain", p.TireMaintain)
	//轮胎维修列表
	http.HandleFunc("/tire/maintainlist", p.TireMaintainList)
	//轮胎维修详情
	http.HandleFunc("/tire/maintaindetail", p.TireMaintainDetail)
	//轮胎导入
	http.HandleFunc("/tire/import", p.TireImport)
	//分配轮胎给下属车队
	http.HandleFunc("/tire/assign", p.TireAssign)

	//传感器管理
	//传感器最新报警信息
	http.HandleFunc("/sensor/lastwarning", p.SensorLastWarning)

	//账号管理
	//账号列表
	http.HandleFunc("/customer/list", p.CustomerList)
	http.HandleFunc("/customer/add", p.CustomerAdd)
	http.HandleFunc("/customer/edit", p.CustomerEdit)
	http.HandleFunc("/customer/remove", p.CustomerRemove)
	http.HandleFunc("/customer/changepassword", p.CustomerChangePassword)
	http.HandleFunc("/customer/bindwechat", p.CustomerBindWechat)
	http.HandleFunc("/customer/unbindwechat", p.CustomerUnbindWechat)
	http.HandleFunc("/customer/loginhistory", p.CustomerLoginHistory)
	http.HandleFunc("/customer/driverunbindminiprogram", p.DriverUnbindMiniProgram)

	//报警管理
	http.HandleFunc("/tirewarning/list", p.TireWarningList)
	http.HandleFunc("/tirewarning/list/v2", p.TireWarningListV3)
	http.HandleFunc("/tirewarning/detail", p.TireWarningDetail)
	http.HandleFunc("/tirewarning/handle", p.TireWarningHandle)
	http.HandleFunc("/tirewarning/makecall", p.TireWarningMakeCall)
	http.HandleFunc("/tirewarning/new", p.TireWarningNew)
	http.HandleFunc("/tirewarning/setconcernedteams", p.TireWarningSetConcernedTeams)
	http.HandleFunc("/tirewarning/concernedteams", p.TireWarningConcernedTeams)
	http.HandleFunc("/tirewarning/setconcernedtypes", p.TireWarningSetConcernedTypes)
	http.HandleFunc("/tirewarning/concernedtypes", p.TireWarningConcernedTypes)
	http.HandleFunc("/tirewarning/setmail", p.TireWarningSetMail)
	http.HandleFunc("/tirewarning/mail", p.TireWarningMail)

	//场站管理类
	http.HandleFunc("/maintenancesite/list", p.MaintenanceSiteList)
	http.HandleFunc("/maintenancesite/add", p.MaintenanceSiteAdd)
	http.HandleFunc("/maintenancesite/edit", p.MaintenanceSiteEdit)
	http.HandleFunc("/maintenancesite/remove", p.MaintenanceSiteRemove)
	http.HandleFunc("/maintenancesite/near", p.MaintenanceSiteNear)

	//仓库管理类
	http.HandleFunc("/warehouse/list", p.WareHouseList)
	http.HandleFunc("/warehouse/add", p.WareHouseAdd)
	http.HandleFunc("/warehouse/edit", p.WareHouseEdit)
	http.HandleFunc("/warehouse/delete", p.WareHouseDelete)

	//里程类
	//传感器里程
	http.HandleFunc("/mileage/sensor", p.MileageSensor)
	//里程统计
	http.HandleFunc("/mileage/statistics", p.MileageStatistics)

	//报表类
	//里程报表
	http.HandleFunc("/report/mileage", p.ReportMillage)
	//报警报表
	http.HandleFunc("/report/warning", p.ReportWarning)
	//异常运行情况统计报表
	http.HandleFunc("/report/abnormaloperation", p.ReportAbnormalOperation)
	//工作时间统计
	http.HandleFunc("/report/worktime", p.ReportWorkTime)

	//下发指令管理类
	http.HandleFunc("/command/list", p.CommandList)

	//设备安装维护类
	//设备安装
	http.HandleFunc("/mainten/install", p.MaintainInstall)         //老接口，待取消
	http.HandleFunc("/mainten/installlist", p.MaintainInstallList) //老接口，待取消
	http.HandleFunc("/mainten/installinfo", p.MaintainInstallInfo) //老接口，待取消
	http.HandleFunc("/maintain/install", p.MaintainInstall)
	http.HandleFunc("/maintain/installlist", p.MaintainInstallList)
	http.HandleFunc("/maintain/installinfo", p.MaintainInstallInfo)
	//胎纹检查
	http.HandleFunc("/maintain/check", p.MaintainCheck)
	//轮胎修补
	http.HandleFunc("/maintain/fixtire", p.MaintainFixTire)
	http.HandleFunc("/maintain/fixtirelist", p.MaintainFixTireList)
	http.HandleFunc("/maintain/fixtireinfo", p.MaintainFixTireInfo)
	http.HandleFunc("/maintain/exchangetire", p.MaintainExchangeTire)
	http.HandleFunc("/maintain/exchangetirelist", p.MaintainExchangeTireList)
	http.HandleFunc("/maintain/exchangetireinfo", p.MaintainExchangeTireInfo)
	http.HandleFunc("/maintain/fixvalve", p.MaintainFixValve)
	http.HandleFunc("/maintain/fixvalvelist", p.MaintainFixValveList)
	http.HandleFunc("/maintain/fixvalveinfo", p.MaintainFixValveInfo)
	http.HandleFunc("/maintain/inflate", p.MaintainInflate)
	http.HandleFunc("/maintain/inflatelist", p.MaintainInflateList)
	http.HandleFunc("/maintain/inflateinfo", p.MaintainInflateInfo)
	http.HandleFunc("/maintain/reportaccident", p.MaintainReportAccident)
	http.HandleFunc("/maintain/reportaccidentlist", p.MaintainReportAccidentList)
	http.HandleFunc("/maintain/reportaccidentsetstatus", p.MaintainReportaccidentSetStatus)
	http.HandleFunc("/maintain/reportaccidentprogress", p.MaintainReportaccidentProgress)

	//开始监听
	var err error
	sPort := fmt.Sprintf(":%d", port)
	zLog(nil, "开始监听端口:", sPort, " HTTPS:", p.cfg.HTTPS)
	if p.cfg.HTTPS {
		err = http.ListenAndServeTLS(sPort, p.cfg.CertFile, p.cfg.KeyFile, nil)
	} else {
		err = http.ListenAndServe(sPort, nil)
	}
	if err != nil {
		zLog(nil, "HTTPS监听失败:", err)
	}
}

// API接口函数------------------------------------------------------------------------
// 数据查询类
// 所有接收器的最新位置
func (p *HttpListener) ReceiverPositions(w http.ResponseWriter, req *http.Request) {
	if _, userId, ok := p.commonCheck(&w, req); ok {
		req.ParseForm()

		cid := req.FormValue("cid")
		tid := req.FormValue("tid")
		gpsType := req.FormValue("type")
		if gpsType != GpsWGS84 && gpsType != GpsGCJ02 {
			gpsType = GpsBd09
		}
		page := req.FormValue("page")
		count := req.FormValue("count")
		t := req.FormValue("t")

		var iCid, iPage, iCount, iT int
		var err error

		iCid, err = strconv.Atoi(cid)
		if err != nil {
			iCid = 0
		}
		iPage, err = strconv.Atoi(page)
		if err != nil {
			iPage = 0
		}
		iCount, err = strconv.Atoi(count)
		if err != nil {
			iCount = 100
		}
		iT, err = strconv.Atoi(t)
		if err != nil {
			iT = 0
		}

		total, res := p.dbo.receiverPositions(iCid, tid, gpsType, userId, iPage, iCount, iT)
		ret := make(map[string]interface{})
		ret["errcode"] = 0
		ret["total"] = total
		ret["receivers"] = res

		buf, _ := json.Marshal(ret)
		w.Write(buf)
	}
}

// 接收器最新状态
func (p *HttpListener) ReceiverLastStatus(w http.ResponseWriter, req *http.Request) {
	if language, userId, ok := p.commonCheck(&w, req); ok {
		req.ParseForm()

		rid := req.FormValue("receiver")
		gpsType := req.FormValue("type") //坐标系类别，默认为百度
		if gpsType == "" {
			gpsType = GpsBd09
		}
		if p.checkFields(&w, language, rid) {
			if p.dbo.userHaveReceiver(userId, rid) {
				//如果用户拥有此设备
				res := p.dbo.receiverLastStatus(rid, gpsType)

				var vma float32
				res.ErrorCode = 0
				if res.Rid == "" {
					//虚拟设备或者该设备还没有上传数据
					res.Rid = rid
					res.RType = p.dbo.receiverType(rid)
					res.Status = -1
				}
				//获取设备的车队名，这里后期可以优化
				_, res.Team = p.dbo.getTeamNameByRid(rid)
				if res.Team == "" {
					_, res.Team = p.dbo.getCompanyNameByRid(rid)
				}
				_, res.Driver, res.Plate, res.Frame, res.ReceiverMileage, vma = p.dbo.receiverTeamAndPlateNo(rid)
				res.VehicleMileage = float64(vma)
				if res.Plate == "" {
					res.Plate = rid
				}
				buf, _ := json.Marshal(res)
				w.Write(buf)

			} else {
				sErr := p.makeResultStr(1008, "您没有该设备", language)
				w.Write([]byte(sErr))
			}
		}
	}
}

type TrackResultT struct {
	Errcode int         `json:"errcode"`
	Mileage float64     `json:"mileage"`
	Tracks  []LocationT `json:"tracks"`
}

// 计算里程
func (p *TrackResultT) CalcMileage() {
	var g gps.GPS
	p.Mileage = 0.0
	if p.Tracks == nil || len(p.Tracks) == 0 {
		return
	}

	var lastLat, lastLng float64
	for _, v := range p.Tracks {
		if lastLat == 0.0 && lastLng == 0.0 {
			lastLat, lastLng = v.Lat, v.Lng
		} else {
			p.Mileage += g.Distance(v.Lat, v.Lng, lastLat, lastLng)
			lastLat, lastLng = v.Lat, v.Lng
		}
	}

}

// 查询接收器历史轨迹
func (p *HttpListener) ReceiverTrack(w http.ResponseWriter, req *http.Request) {
	if language, userId, ok := p.commonCheck(&w, req); ok {
		req.ParseForm()

		today := time.Now().Format("060102")
		rid := req.FormValue("receiver")
		sDate := req.FormValue("date")
		gpsType := req.FormValue("type") //坐标系类别，默认为百度
		if gpsType == "" {
			gpsType = GpsBd09
		}
		if sDate == "" {
			sDate = today
		}
		iDate, _ := strconv.Atoi(sDate)
		if p.checkFields(&w, language, rid) {
			if p.dbo.userHaveReceiver(userId, rid) {
				var ret TrackResultT
				ret.Tracks = p.dbo.receiverTrack(rid, iDate, gpsType)
				if ret.Tracks == nil || len(ret.Tracks) == 0 {
					sErr := p.makeResultStr(1005, "本日无轨迹数据", language)
					w.Write([]byte(sErr))
				} else {

					ret.Errcode = 0
					ret.Mileage = 0.0

					if sDate == today {
						//如果是查询当日里程，则直接计算
						ret.CalcMileage()
					} else {
						//历史里程从数据库中读取
						ret.Mileage = p.dbo.receiverMileage(rid, iDate)
						if ret.Mileage == 0.0 {
							//如果数据库中的为零，可能是数据库中计算的有问题，则重新计算一次
							ret.CalcMileage()
						}
					}
					//ret["tracks"] = res

					buf, _ := json.Marshal(ret)
					w.Write(buf)
				}
			} else {
				sErr := p.makeResultStr(1008, "您没有该设备", language)
				w.Write([]byte(sErr))
			}
		}
	}
}

// 查询接收器历史数据
func (p *HttpListener) ReceiverTireDataHistory(w http.ResponseWriter, req *http.Request) {
	if language, userId, ok := p.commonCheck(&w, req); ok {
		req.ParseForm()

		rid := req.FormValue("receiver")
		sDate := req.FormValue("date")
		if sDate == "" {
			sDate = time.Now().Format("060102")
		}
		iDate, _ := strconv.Atoi(sDate)
		if p.checkFields(&w, language, rid) {
			if p.dbo.userHaveReceiver(userId, rid) {
				res := p.dbo.receiverTireDataHistory(rid, iDate)
				if res == nil {
					sErr := p.makeResultStr(1005, "本日无数据", language)
					w.Write([]byte(sErr))
				} else {
					ret := make(map[string]interface{})
					ret["errcode"] = 0
					ret["datas"] = res

					buf, _ := json.Marshal(ret)
					w.Write(buf)
				}
			} else {
				sErr := p.makeResultStr(1008, "您没有该设备", language)
				w.Write([]byte(sErr))
			}
		}
	}
}

// 查询传感器胎温胎压历史数据
func (p *HttpListener) SensorDataHistory(w http.ResponseWriter, req *http.Request) {
	if language, _, ok := p.commonCheck(&w, req); ok {
		req.ParseForm()

		sid := req.FormValue("sensor")
		sdate := req.FormValue("date")
		if sdate == "" {
			sdate = time.Now().Format("060102")
		}
		iDate, _ := strconv.Atoi(sdate)
		if p.checkFields(&w, language, sid) {
			//if p.dbo.userHaveReceiver(userId, sid) {
			res := p.dbo.sensorDataHistory(sid, iDate)
			if res == nil {
				sErr := p.makeResultStr(1005, "本日无数据", language)
				w.Write([]byte(sErr))
			} else {
				ret := make(map[string]interface{})
				ret["errcode"] = 0
				ret["datas"] = res

				buf, _ := json.Marshal(ret)
				w.Write(buf)
			}
		}
	}
}

// 查询传感器胎温胎压历史数据
func (p *HttpListener) SensorDataHistory2(w http.ResponseWriter, req *http.Request) {
	if language, userid, ok := p.commonCheck(&w, req); ok {
		req.ParseForm()

		rid := req.FormValue("receiver")
		cardid := req.FormValue("cardid")
		sn := req.FormValue("sn")
		sdate := req.FormValue("date")
		if sdate == "" {
			sdate = time.Now().Format("060102")
		}

		iDate, _ := strconv.Atoi(sdate)
		if p.checkFields(&w, language, rid, sn) {
			//if p.dbo.userHaveReceiver(userId, sid) {
			isn, err := strconv.Atoi(sn)
			if err != nil {
				isn = 0
			}
			icardid, err := strconv.Atoi(cardid)
			if err != nil {
				icardid = 0
			}

			res := p.dbo.sensorDataHistory2(rid, icardid, isn, iDate)
			resLen := len(res)

			//如果只有一个0值，则显示无数据
			if resLen == 1 && (res[0].Pres == 0.00 || res[0].Temp == 0 || res[0].Temp > 120) {
				res = nil
				resLen = 0
			}

			//非超级用户，要处理数据为0的情况
			if p.dbo.userType(userid) != UserTypeSystemUser {
				for i := 0; i < resLen; i++ {

					if res[i].Pres == 0.00 && res[i].Temp == 205 {
						if i > 0 {
							res[i].Pres, res[i].Temp = res[i-1].Pres, res[i-1].Temp
						}
						continue
					}
					if res[i].Pres == 0.00 {
						//如果值为0，则判断前后是否为0
						if i == 0 {
							//第一个
							if res[i+1].Pres != 0.00 {
								res[i].Pres = res[i+1].Pres
							}
						} else if i == resLen-1 {
							//最后一个
							if res[i-1].Pres != 0.00 {
								res[i].Pres = res[i-1].Pres
							}
						} else {
							if res[i+1].Pres != 0.00 && res[i-1].Pres != 0.00 {
								res[i].Pres = res[i-1].Pres
							}
						}
					}
					if res[i].Temp == 0 {
						//如果值为0，则判断前后是否为0
						if i == 0 {
							//第一个
							if res[i+1].Temp != 0 {
								res[i].Temp = res[i+1].Temp
							}
						} else if i == resLen-1 {
							//最后一个
							if res[i-1].Temp != 0 {
								res[i].Temp = res[i-1].Temp
							}
						} else {
							if res[i+1].Temp != 0 && res[i-1].Temp != 0 {
								res[i].Temp = res[i-1].Temp
							}
						}
					} else if res[i].Temp > 120 && resLen >= 5 {
						//简单起见，只处理5个及以上的数据点
						//大于120，有可能是误报
						//连续3个以下为120时，认为是误报，将其修改为前一个值或最后一个值
						iErr := 0
						j := i
						for ; j < resLen; j++ {
							//j之所以从i开始，是因为不用判断i+1是否越界
							if res[j].Temp > 120 {
								iErr++
							} else {
								break
							}
						}
						//连接3个以上（4个开始），认为是真实的数据，不做屏蔽处理
						if iErr <= 3 {
							//修正后的值
							fixTemp := 0
							if i == 0 {
								//如果第一个值异常，则以后面第一个正常值为准
								fixTemp = res[j].Temp
							} else {
								//否则以
								fixTemp = res[i-1].Temp
							}
							for j := 0; j < iErr; j++ {
								res[i+j].Temp = fixTemp
							}
						}
					}
				}
			}

			if res == nil {
				sErr := p.makeResultStr(1005, "本日无数据", language)
				w.Write([]byte(sErr))
			} else {
				ret := make(map[string]interface{})
				ret["errcode"] = 0
				ret["datas"] = res

				buf, _ := json.Marshal(ret)
				w.Write(buf)
			}
		}
	}
}

// 轮胎信息查询
type TireInfoT struct {
	ErrCode     int       `json:"errcode"`
	CardId      int       `json:"cardid"`
	Sn          int       `json:"sn"`
	BrandID     int       `json:"brandid"`
	Brand       string    `json:"brand"`
	Model       string    `json:"model"`
	Pattern     string    `json:"pattern"`
	TireNo      string    `json:"tno"` //胎号
	Dot         string    `json:"dot"`
	RFID        string    `json:"rfid"`
	Mileage     float32   `json:"mileage"`     //里程
	Depth       []float32 `json:"depths"`      //花纹深度，单位毫米
	Operator    string    `json:"operator"`    //安装人员
	OperateTime int       `json:"operatetime"` //安装时间
	Status      int       `json:"status"`      //轮胎状态
}

func (p *HttpListener) TireInfo(w http.ResponseWriter, req *http.Request) {
	if language, _, ok := p.commonCheck(&w, req); ok {
		req.ParseForm()
		sid := req.FormValue("sid")
		rid := req.FormValue("rid")
		if p.checkFields(&w, language, rid, sid) {
			ti, err := p.dbo.tireInfo(rid, sid)
			if err != nil {
				sErr := p.makeResultStr(2001, "数据查询无结果", language)
				w.Write([]byte(sErr))
			} else {
				buf, _ := json.Marshal(ti)
				w.Write(buf)
			}
		}
	}
}

// 接收器查询
func (p *HttpListener) QueryReceiverId(w http.ResponseWriter, req *http.Request) {
	if language, _, ok := p.commonCheck(&w, req); ok {
		req.ParseForm()
		rid := req.FormValue("rid")
		if p.checkFields(&w, language, rid) {
			rids := p.dbo.queryReceiverId(rid)

			ret := make(map[string]interface{})
			ret["errcode"] = 0
			ret["rids"] = rids

			buf, _ := json.Marshal(ret)
			w.Write(buf)
		}
	}
}

// 模糊查询车牌号与设备号，车牌号优先，只返回10条纪录，不支持分页
func (p *HttpListener) Properties(w http.ResponseWriter, req *http.Request) {
	if language, _, ok := p.commonCheck(&w, req); ok {
		req.ParseForm()
		cid := req.FormValue("cid")
		tid := req.FormValue("tid")
		key := req.FormValue("key")
		if p.checkFields(&w, language, cid) {
			var iCid int
			var err error

			iCid, err = strconv.Atoi(cid)
			if err != nil {
				p.wrongParameter(&w, err, language)
				return
			}

			props := p.dbo.propreties(iCid, tid, key)
			buf := p.makeResultBuffer("datas", props)
			w.Write(buf)
		}
	}
}

// 设备管理----------------------------------------------------------------------------
// 批量导入接收器
func (p *HttpListener) ReceiverBatchCreate(w http.ResponseWriter, req *http.Request) {
	if language, userId, ok := p.commonCheck(&w, req); ok {
		var sErr string

		//只有系统管理员有些权限
		userType := p.dbo.userType(userId)
		if userType != UserTypeSystemUser {
			sErr = p.makeResultStr(1014, "无此权限", language)
			w.Write([]byte(sErr))
			return
		}

		req.ParseForm()

		rtype := req.FormValue("type")
		project := req.FormValue("project")
		manufacturer := req.FormValue("manufacturer")
		year := req.FormValue("year")
		week := req.FormValue("week")
		startNumber := req.FormValue("startnumber")
		endNumber := req.FormValue("endnumber")

		var err error
		var paramOk bool
		var iType, iProject, iManufacturer, iYear, iWeek, iStartNumber, iEndNumber int

		//严格检查参数！！
		if p.checkFields(&w, language, rtype, project, manufacturer, year, week, startNumber, endNumber) {
			paramOk = false

			iType, err = strconv.Atoi(rtype)
			if err == nil {
				iProject, err = strconv.Atoi(project)
				if err == nil {
					iManufacturer, err = strconv.Atoi(manufacturer)
					if err == nil {
						iYear, err = strconv.Atoi(year)
						if err == nil {
							iWeek, err = strconv.Atoi(week)
							if err == nil {
								iStartNumber, err = strconv.Atoi(startNumber)
								if err == nil {
									iEndNumber, err = strconv.Atoi(endNumber)
								}
							}
						}
					}
				}
			}

			if err == nil {
				if (iType >= 1 && iType <= 5) &&
					(iProject >= 0 && iProject <= 99) &&
					(iManufacturer >= 0 && iManufacturer <= 9) &&
					(iYear >= 0 && iYear <= 9) &&
					(iWeek >= 1 && iWeek <= 99) &&
					(iStartNumber >= 0 && iStartNumber <= 9999) &&
					(iEndNumber >= 0 && iEndNumber <= 9999) &&
					(iEndNumber > iStartNumber) {
					paramOk = true
				}
			}

			if !paramOk {
				sErr = p.makeResultStr(1009, "参数错误", language)
				w.Write([]byte(sErr))
				return
			}

			//参数正确
			prefix := fmt.Sprintf("0%d%02d%d%d%02d", iType, iProject, iManufacturer, iYear, iWeek)
			count, failedCount, faileds := p.dbo.receiverBatchCreate(iType, prefix, iStartNumber, iEndNumber)

			var ret map[string]interface{} = make(map[string]interface{})

			ret["errcode"] = 0
			ret["count"] = count
			ret["failedcount"] = failedCount
			ret["faileds"] = faileds

			buf, _ := json.Marshal(ret)
			w.Write(buf)
		}
	}
}

// 获取接收器列表(App端)
func (p *HttpListener) Receivers(w http.ResponseWriter, req *http.Request) {
	if _, userId, ok := p.commonCheck(&w, req); ok {
		req.ParseForm()
		rid := req.FormValue("rid")
		page := req.FormValue("page")
		if page == "" {
			page = "0"
		}
		iPage, err := strconv.Atoi(page)
		if err != nil {
			//输入的page数不正确，设置为0
			iPage = 0
		}

		res := p.dbo.receivers(userId, rid, iPage)
		ret := make(map[string]interface{})
		ret["errcode"] = 0
		ret["receivers"] = res

		buf, _ := json.Marshal(ret)
		w.Write(buf)
	}
}

// 获取接收器列表V2(App端)
func (p *HttpListener) ReceiversV2(w http.ResponseWriter, req *http.Request) {
	if _, userId, ok := p.commonCheck(&w, req); ok {
		req.ParseForm()
		rid := req.FormValue("rid")
		page := req.FormValue("page")
		if page == "" {
			page = "0"
		}
		iPage, err := strconv.Atoi(page)
		if err != nil {
			//输入的page数不正确，设置为0
			iPage = 0
		}

		res := p.dbo.receiversV2(userId, rid, iPage)
		ret := make(map[string]interface{})
		ret["errcode"] = 0
		ret["receivers"] = res

		buf, _ := json.Marshal(ret)
		w.Write(buf)
	}
}

// 获取接收器列表(PC端)
func (p *HttpListener) ReceiverList(w http.ResponseWriter, req *http.Request) {
	if language, userId, ok := p.commonCheck(&w, req); ok {
		req.ParseForm()
		cid := req.FormValue("cid")
		tid := req.FormValue("tid")
		rid := req.FormValue("rid")
		iccid := req.FormValue("iccid")
		plate := req.FormValue("plate")
		online := req.FormValue("online")
		page := req.FormValue("page")
		export := req.FormValue("export")

		var iPage, iExport, iOnline int
		var err error

		iPage, err = strconv.Atoi(page)
		if err != nil {
			//输入的page数不正确，设置为0
			iPage = 0
		}

		iOnline, err = strconv.Atoi(online)
		if err != nil || iOnline < -1 || iOnline > 1 {
			iOnline = 0
		}

		iExport, err = strconv.Atoi(export)
		//iExport 只有0/1
		if err != nil || iExport != 1 {
			iExport = 0
		}

		if p.checkFields(&w, language, cid) {
			iCid, err := strconv.Atoi(cid)
			if err != nil {
				sErr := p.makeResultStr(1009, "参数错误", language)
				w.Write([]byte(sErr))
				return
			}

			if p.dbo.userType(userId) != UserTypeSystemUser && iCid == 0 {
				sErr := p.makeResultStr(1014, "无此权限", language)
				w.Write([]byte(sErr))
				return
			}

			total, res := p.dbo.receiverList( /*userId,*/ iCid, tid, rid, iccid, plate, iOnline, iPage, iExport)
			if iExport == 1 {
				//导出
				var eq ExportQuery
				eq.FieldMaps = []ExportQueryFieldMap{
					{Title: "接收器ID", Key: "rid", Format: "%s"},
					{Title: "车型", Key: "type", Processor: VehicleTypeToString},
					{Title: "车牌", Key: "plate"},
					{Title: "总里程(公里)", Key: "mileage", Format: "%.2f"},
					{Title: "ICCID", Key: "iccid", Format: "\t%s"},
					{Title: "最后通讯时间", Key: "lt", Format: "%.0f", Processor: func(v string) string {

						iv, err := strconv.Atoi(v)
						if err != nil || iv == 0 {
							return ""
						}
						return TimeStampToString(iv, "")
					}},
				}

				fileName := fmt.Sprintf("receivers-%d.csv", time.Now().Unix())
				err = eq.Export(res, p.cfg.ExportDir+fileName)
				if err != nil {
					ret := p.makeResultStr2(1102, "数据导出失败", err.Error(), language)
					w.Write([]byte(ret))
				} else {

					url := p.cfg.ExportUrl + fileName
					buf := p.makeResultRedirect(url)

					w.Write(buf)
				}
			} else {
				ret := make(map[string]interface{})
				ret["errcode"] = 0
				ret["total"] = total
				ret["receivers"] = res

				buf, _ := json.Marshal(ret)
				w.Write(buf)
			}
		}
	}
}

// 获取接收器列表(for大屏展示)
func (p *HttpListener) ReceiverView(w http.ResponseWriter, req *http.Request) {
	if language, userId, ok := p.commonCheck(&w, req); ok {
		req.ParseForm()
		cid := req.FormValue("cid")
		tid := req.FormValue("tid")
		page := req.FormValue("page")
		count := req.FormValue("count")

		var iPage, iCount int
		var err error

		iPage, err = strconv.Atoi(page)
		if err != nil {
			//输入的page数不正确，设置为0
			iPage = 0
		}
		iCount, err = strconv.Atoi(count)
		if err != nil {
			iCount = 50
		}

		if p.checkFields(&w, language, cid) {
			iCid, err := strconv.Atoi(cid)
			if err != nil {
				p.wrongParameter(&w, err, language)
				return
			}

			if p.dbo.userType(userId) != UserTypeSystemUser && iCid == 0 {
				sErr := p.makeResultStr(1014, "无此权限", language)
				w.Write([]byte(sErr))
				return
			}

			total, res := p.dbo.receiverView( /*userId,*/ iCid, tid, iPage, iCount)

			ret := make(map[string]interface{})
			ret["errcode"] = 0
			ret["total"] = total
			ret["receivers"] = res

			buf, _ := json.Marshal(ret)
			w.Write(buf)
		}
	}
}

// 接收器类别
func (p *HttpListener) ReceiverType(w http.ResponseWriter, req *http.Request) {
	if language, _, ok := p.commonCheck(&w, req); ok {
		var sErr string

		req.ParseForm()

		rid := req.FormValue("rid")

		if p.checkFields(&w, language, rid) {
			iType := p.dbo.receiverType(rid)
			if iType >= 0 {
				sErr = fmt.Sprintf(`{"errcode":0,"type":%d}`, iType)
			} else {
				sErr = p.makeResultStr(1004, "未找到该设备", language)
			}

			w.Write([]byte(sErr))
		}
	}
}

// 接收器作废
func (p *HttpListener) ReceiverInvalid(w http.ResponseWriter, req *http.Request) {
	if language, userid, ok := p.commonCheck(&w, req); ok {
		req.ParseForm()

		cid := req.FormValue("cid")
		tid := req.FormValue("tid")
		rid := req.FormValue("rid")
		valid := req.FormValue("valid")
		idate := req.FormValue("date")
		itime := req.FormValue("time")
		reason := req.FormValue("reason")

		var sErr string
		var err error

		if p.checkFields(&w, language, cid, rid, idate, itime, valid) {
			var iCid, iValid, iDate, iTime int

			//检查参数合法性
			iCid, err = strconv.Atoi(cid)
			if err != nil {
				sErr = p.makeResultStr(1009, "参数错误", language)
			} else {
				iValid, err = strconv.Atoi(valid)
				if err != nil {
					sErr = p.makeResultStr(1009, "参数错误", language)
				} else {
					iDate, err = strconv.Atoi(idate)
					if err != nil {
						sErr = p.makeResultStr(1009, "参数错误", language)
					} else {
						iTime, err = strconv.Atoi(itime)
						if err != nil {
							sErr = p.makeResultStr(1009, "参数错误", language)
						}
					}
				}
			}
			if sErr != "" {
				w.Write([]byte(sErr))
				return
			}

			err = p.dbo.receiverInvalid(userid, iCid, tid, rid, iDate, iTime, iValid, reason)
			if err == nil {
				sErr = `{"errcode":0}`
			} else {
				sErr = p.makeResultStr(1101, "操作失败："+err.Error(), language)
			}

			w.Write([]byte(sErr))
		}
	}
}

// 绑定传感器
type BindSensorT struct {
	Sid    string `json:"sid"`
	CardId int    `json:"cardid"`
	SN     int    `json:"sn"`
}
type ReceiverBindSensorT struct {
	Rid     string        `json:"rid"`
	RType   int           `json:"type"`
	Mode    int           `json:"mode"` //操作模式，1：设置；2：删除，默认为1
	Sensors []BindSensorT `json:"sensors"`
}

func (p *HttpListener) ReceiverBindSensor(w http.ResponseWriter, req *http.Request) {
	if language, _, ok := p.commonCheck(&w, req); ok {
		req.Header.Set("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept")
		w.Header().Add("Access-Control-Allow-Methods", "POST,GET,OPTIONS,DELETE")

		var sErr string
		var rbs, newRbs ReceiverBindSensorT

		//读取请求内容
		buf, err := p.readBody(req)
		if err == nil {
			err = json.Unmarshal(buf, &rbs)
		}
		if err != nil {
			sErr = p.makeResultStr(1102, err.Error(), language)
			w.Write([]byte(sErr))
			return
		}

		newRbs = ReceiverBindSensorT{}
		newRbs.Rid = rbs.Rid
		newRbs.RType = rbs.RType
		newRbs.Mode = rbs.Mode
		if newRbs.Mode == 0 {
			//为了兼容老接口，没有Mode，则默认为1：设置
			rbs.Mode = 1
			newRbs.Mode = 1
		}
		newRbs.Sensors = make([]BindSensorT, 0)
		for _, v := range rbs.Sensors {
			if (v.Sid != "" && rbs.Mode == 1) || (v.Sid == "" && rbs.Mode == 2) {
				newRbs.Sensors = append(newRbs.Sensors, v)
			}
		}
		buf, _ = json.Marshal(newRbs)

		//设置设备类别
		go p.dbo.setReceiverType(newRbs.Rid, newRbs.RType)
		//保存配置关系
		//go p.dbo.saveReceiverSensors(newRbs.Rid, newRbs.Sensors)

		buf, err = p.Post(p.cfg.ReceiverdURL+"/receiver/bindsensor", "", buf)
		if err != nil {
			w.Write([]byte(err.Error()))
		} else {
			w.Write(buf)
		}
	}
}

type ThresholdT struct {
	Pressure    [5][2]float32 `bson:"pres" json:"pressure"`
	Temperature int           `bson:"temp" json:"temperature"`
}

type ReceiverThresholdT struct {
	Rid       string     `json:"rid"`
	Threshold ThresholdT `json:"threshold"`
}

type ReceiverThresholdDBT struct {
	Rid       string     `bson:"rid" json:"rid"`
	Type      int        `bson:"type" json:"type"`
	Threshold ThresholdT `bson:"threshold" json:"threshold"`
}

// 查询高低压和高温阀值
func (p *HttpListener) ReceiverThresholt(w http.ResponseWriter, req *http.Request) {

	const DefaultPressureThresholdHigh float32 = 12.1

	const DefaultPressureThresholdLow float32 = 6.9

	const DefaultTemperatureThreshold int = 70

	if language, _, ok := p.commonCheck(&w, req); ok {
		rid := req.FormValue("rid")
		if p.checkFields(&w, language, rid) {
			rt, err := p.dbo.receiverThreshold(rid)
			if err != nil {
				sErr := p.makeResultStr2(2000, "查询失败", err.Error(), language)
				w.Write([]byte(sErr))
			} else {

				isZero := true
				if rt.Threshold.Temperature == 0 {
					for i := 0; i < 5 && isZero; i++ {
						for j := 0; j < 2; j++ {
							if rt.Threshold.Pressure[i][j] != 0 {
								isZero = false
								break
							}
						}
					}
				} else {
					isZero = false
				}
				if isZero {
					rt.Threshold.Temperature = DefaultTemperatureThreshold
					for i := 0; i < 5; i++ {
						rt.Threshold.Pressure[i][0] = DefaultPressureThresholdHigh
						rt.Threshold.Pressure[i][1] = DefaultPressureThresholdLow
					}
				}

				ret := make(map[string]interface{})
				ret["errcode"] = 0
				ret["data"] = rt

				buf, _ := json.Marshal(ret)
				w.Write(buf)
			}
		}
	}
}

// 设置高低压和高温阀值
func (p *HttpListener) ReceiverSetThreshold(w http.ResponseWriter, req *http.Request) {
	if language, _, ok := p.commonCheck(&w, req); ok {
		req.Header.Set("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept")
		w.Header().Add("Access-Control-Allow-Methods", "POST,GET,OPTIONS,DELETE")

		var sErr string
		var rt ReceiverThresholdT

		//读取请求内容
		buf, err := p.readBody(req)
		if err == nil {
			err = json.Unmarshal(buf, &rt)
		}
		if err != nil {
			sErr = p.makeResultStr2(1009, "参数错误", err.Error(), language)
			w.Write([]byte(sErr))
			return
		}
		//检查参数
		//默认的高压阀值
		const DefaultPressureThresholdHigh float32 = 12.1
		//默认的低压阀值
		const DefaultPressureThresholdLow float32 = 6.9
		//默认的高温阀值
		const DefaultTemperatureThreshold int = 70

		if p.dbo.receiverType(rt.Rid) == -1 {
			sErr = p.makeResultStr(1004, "未找到该设备", language)
			w.Write([]byte(sErr))
			return
		}

		for i := 0; i < 5; i++ {
			if rt.Threshold.Pressure[i][0] == 0 {
				rt.Threshold.Pressure[i][0] = DefaultPressureThresholdHigh
			}
			if rt.Threshold.Pressure[i][1] == 0 {
				rt.Threshold.Pressure[i][1] = DefaultPressureThresholdLow
			}
		}
		if rt.Threshold.Temperature == 0 {
			rt.Threshold.Temperature = DefaultTemperatureThreshold
		}

		p.dbo.saveReceiverThreshold(rt.Rid, rt.Threshold.Pressure, rt.Threshold.Temperature)
		sErr = p.makeResultStr(0, "", language)
		w.Write([]byte(sErr))
		/*
			buf, _ = json.Marshal(rt)


			buf, err = p.Post(p.cfg.ReceiverdURL+"/receiver/setthreshold", "", buf)
			if err != nil {
				w.Write([]byte(err.Error()))
			} else {
				w.Write(buf)
			}
		*/
	}
}

// 接收器的传感器信息
func (p *HttpListener) ReceiverSensors(w http.ResponseWriter, req *http.Request) {
	if language, _, ok := p.commonCheck(&w, req); ok {
		req.ParseForm()

		rid := req.FormValue("rid")

		if p.checkFields(&w, language, rid) {
			res := p.dbo.receiverSensors(rid)
			ret := make(map[string]interface{})
			ret["errcode"] = 0
			ret["datas"] = res

			buf, _ := json.Marshal(ret)

			w.Write(buf)
		}
	}
}

// 删除指定轮位的数据
func (p *HttpListener) ReceiverRemoveSN(w http.ResponseWriter, req *http.Request) {
	if language, _, ok := p.commonCheck(&w, req); ok {
		req.ParseForm()

		rid := req.FormValue("rid")
		cardid := req.FormValue("cardid")
		sn := req.FormValue("sn")

		var sErr string
		var err error

		if p.checkFields(&w, language, rid, cardid, sn) {
			var iCardID, iSN int

			//检查参数合法性
			iCardID, err = strconv.Atoi(cardid)
			if err != nil {
				sErr = p.makeResultStr(1009, "参数错误", language)
			} else {
				iSN, err = strconv.Atoi(sn)
				if err != nil {
					sErr = p.makeResultStr(1009, "参数错误", language)
				}
			}
			if sErr != "" {
				w.Write([]byte(sErr))
				return
			}

			err = p.dbo.receiverRemoveSN(rid, iCardID, iSN)
			if err == nil {
				sErr = `{"errcode":0}`
			} else {
				sErr = p.makeResultStr(1101, "操作失败："+err.Error(), language)
			}

			w.Write([]byte(sErr))
		}
	}
}

// 更换接收器
func (p *HttpListener) ReceiverExchange(w http.ResponseWriter, req *http.Request) {
	if language, userid, ok := p.commonCheck(&w, req); ok {
		req.ParseForm()

		cid := req.FormValue("cid")
		tid := req.FormValue("tid")
		oldRid := req.FormValue("oldrid")
		newRid := req.FormValue("newrid")
		invalid := req.FormValue("invalid")
		recode := req.FormValue("recode")
		edate := req.FormValue("date")
		etime := req.FormValue("time")
		reason := req.FormValue("reason")

		var sErr string
		var err error

		if p.checkFields(&w, language, cid, oldRid, newRid, edate, etime, invalid) {
			var iCid, iInvalid, iRecode, iDate, iTime int

			//检查参数合法性
			iInvalid, err = strconv.Atoi(invalid)
			if err != nil {
				iInvalid = 0
			}
			iRecode, err = strconv.Atoi(recode)
			if err != nil {
				iRecode = 0
			}
			iCid, err = strconv.Atoi(cid)
			if err == nil {
				iDate, err = strconv.Atoi(edate)
				if err == nil {
					iTime, err = strconv.Atoi(etime)
				}
			}
			if err != nil {
				sErr = p.makeResultStr(1009, "参数错误", language)
			}

			if err == nil && oldRid == newRid {
				sErr = p.makeResultStr2(1009, "参数错误", "新旧设备号不能相同", language)
			}
			if sErr != "" {
				w.Write([]byte(sErr))
				return
			}

			err = p.dbo.receiverExchange(userid, iCid, tid, oldRid, newRid, iDate, iTime, iInvalid, reason)
			if err == nil {
				sErr = `{"errcode":0}`
				//如果需要下发对码
				if iRecode == 1 {
					cmd := make(map[string]interface{})
					cmd["rid"] = newRid
					cmd["type"] = p.dbo.receiverType(newRid)
					cmd["sensors"] = p.dbo.receiverSensors(newRid)

					buf, _ := json.Marshal(cmd)

					_, err = p.Post(p.cfg.ReceiverdURL+"/receiver/bindsensor", "", buf)
					if err != nil {
						sErr = p.makeResultStr2(1101, "操作失败：", err.Error(), language)
					}
				}
			} else {
				sErr = p.makeResultStr2(1101, "操作失败：", err.Error(), language)
			}

			w.Write([]byte(sErr))
		}
	}
}

// 接收器的原始数据
func (p *HttpListener) ReceiverRawData(w http.ResponseWriter, req *http.Request) {
	if _, _, ok := p.commonCheck(&w, req); ok {
		req.ParseForm()

		rid := req.FormValue("rid")
		stype := req.FormValue("type")
		sdate := req.FormValue("date")
		page := req.FormValue("page")

		var err error

		var iPage, iDate int

		//检查参数合法性
		iPage, err = strconv.Atoi(page)
		if err != nil {
			iPage = 0
		}
		iDate, err = strconv.Atoi(sdate)
		if err != nil {
			iDate = 0
		}

		total, res := p.dbo.receiverRawData(rid, stype, iDate, iPage)
		ret := make(map[string]interface{})
		ret["errcode"] = 0
		ret["total"] = total
		ret["datas"] = res

		buf, _ := json.Marshal(ret)
		w.Write(buf)
	}
}

// 接收器批量导入
func (p *HttpListener) ReceiverImport(w http.ResponseWriter, req *http.Request) {
	if language, userid, ok := p.commonCheck(&w, req); ok {
		//只有系统管理员才能够导入
		if p.checkUserType(&w, language, userid) {
			req.ParseForm()

			stype := req.FormValue("type")
			rids := req.FormValue("rids")
			if p.checkFields(&w, language, rids, stype) {

				var sErr string
				var err error
				var iType int

				//检查参数合法性
				iType, err = strconv.Atoi(stype)
				if err != nil {
					sErr = p.makeResultStr(1009, "参数错误", language)
					w.Write([]byte(sErr))
					return
				}
				ridSlice := strings.Split(rids, ",")
				failedCount, faileds := p.dbo.receiverImport(iType, ridSlice)
				ret := make(map[string]interface{})
				ret["errcode"] = 0
				ret["count"] = len(ridSlice)
				ret["failedcount"] = failedCount
				ret["faileds"] = faileds

				buf, _ := json.Marshal(ret)
				w.Write(buf)
			}
		}
	}
}

// 修改接收器类别
func (p *HttpListener) ReceiverChangeType(w http.ResponseWriter, req *http.Request) {
	if language, _, ok := p.commonCheck(&w, req); ok {
		req.ParseForm()

		stype := req.FormValue("type")
		rids := req.FormValue("rids")
		if p.checkFields(&w, language, rids, stype) {

			var sErr string
			var err error
			var iType int

			//检查参数合法性
			iType, err = strconv.Atoi(stype)
			if err != nil {
				sErr = p.makeResultStr(1009, "参数错误", language)
				w.Write([]byte(sErr))
				return
			}
			ridSlice := strings.Split(rids, ",")
			p.dbo.receiverChangeType(iType, ridSlice)
			sErr = p.makeResultStr(0, "", language)

			w.Write([]byte(sErr))
		}
	}
}

// 将接收器划归某公司名下
func (p *HttpListener) ReceiverSetToCompany(w http.ResponseWriter, req *http.Request) {
	if language, userid, ok := p.commonCheck(&w, req); ok {
		//只有系统管理员才能够导入
		if p.checkUserType(&w, language, userid) {
			req.ParseForm()

			cid := req.FormValue("cid")
			tid := req.FormValue("tid")
			rids := req.FormValue("rids")
			if p.checkFields(&w, language, rids, cid) {

				var sErr string
				var err error
				var iCid int

				//检查参数合法性
				iCid, err = strconv.Atoi(cid)
				if err != nil {
					sErr = p.makeResultStr(1009, "参数错误", language)
					w.Write([]byte(sErr))
					return
				}
				ridSlice := strings.Split(rids, ",")
				p.dbo.receiverSetToCompany(iCid, tid, ridSlice)

				sErr = p.makeResultStr(0, "", language)
				w.Write([]byte(sErr))
			}
		}
	}
}

// 将一组接收器从某公司或车队名下移除
func (p *HttpListener) ReceiverRemoveFromCompany(w http.ResponseWriter, req *http.Request) {
	if language, userid, ok := p.commonCheck(&w, req); ok {
		//只有系统管理员才能够导入
		if p.checkUserType(&w, language, userid) {
			req.ParseForm()

			cid := req.FormValue("cid")
			tid := req.FormValue("tid")
			rids := req.FormValue("rids")
			if p.checkFields(&w, language, rids, cid) {

				var sErr string
				var err error
				var iCid int

				//检查参数合法性
				iCid, err = strconv.Atoi(cid)
				if err != nil {
					sErr = p.makeResultStr(1009, "参数错误", language)
					w.Write([]byte(sErr))
					return
				}
				ridSlice := strings.Split(rids, ",")
				p.dbo.receiverRemoveFromCompany(iCid, tid, ridSlice)

				sErr = p.makeResultStr(0, "", language)
				w.Write([]byte(sErr))
			}
		}
	}
}

// 接收器归属
func (p *HttpListener) ReceiverBelong(w http.ResponseWriter, req *http.Request) {
	if language, userid, ok := p.commonCheck(&w, req); ok {
		//只有系统管理员才能够导入
		if p.checkUserType(&w, language, userid) {
			req.ParseForm()
			rid := req.FormValue("rid")

			if p.checkFields(&w, language, rid) {
				data := p.dbo.receiverBelong(rid)
				ret := map[string]interface{}{
					"errcode": 0,
					"data":    data,
				}
				buf, _ := json.Marshal(ret)
				w.Write(buf)
			}
		}
	}
}

// 清空接收器设备
func (p *HttpListener) ReceiverClean(w http.ResponseWriter, req *http.Request) {
	if language, userid, ok := p.commonCheck(&w, req); ok {
		//只有系统管理员才能够导入
		if p.checkUserType(&w, language, userid) {
			req.ParseForm()

			rids := req.FormValue("rids")
			if p.checkFields(&w, language, rids) {
				var sErr string

				ridSlice := strings.Split(rids, ",")
				p.dbo.receiverClean(ridSlice)

				sErr = p.makeResultStr(0, "", language)
				w.Write([]byte(sErr))
			}
		}
	}
}

// 修改设备的服务器IP和端口
func (p *HttpListener) ReceiverSetServer(w http.ResponseWriter, req *http.Request) {
	if language, userid, ok := p.commonCheck(&w, req); ok {
		//只有系统管理员才能够导入
		if p.checkUserType(&w, language, userid) {
			req.ParseForm()

			rids := req.FormValue("rids")
			ip := req.FormValue("ip")
			port := req.FormValue("port")
			all := req.FormValue("all")

			var sErr string

			iAll, err := strconv.Atoi(all)
			if err != nil {
				iAll = 0
			}
			iPort, err := strconv.Atoi(port)
			if err != nil {
				sErr = p.makeResultStr(1009, "参数错误", language)
				w.Write([]byte(sErr))
				return
			}

			if p.checkFields(&w, language, rids, ip, port) {
				ridSlice := strings.Split(rids, ",")
				err = p.dbo.receiverSetServer(ip, iPort, iAll, ridSlice)
				var buf []byte

				if err != nil {
					sErr = p.makeResultStr2(1101, "操作失败", err.Error()+";"+string(buf), language)
				} else {
					sErr = p.makeResultStr(0, "", language)
				}

				w.Write([]byte(sErr))
			}
		}
	}
}

// 查询数据上传频率
func (p *HttpListener) ReceiverUploadFrequncy(w http.ResponseWriter, req *http.Request) {
	if language, _, ok := p.commonCheck(&w, req); ok {
		req.ParseForm()
		rid := req.FormValue("rid")

		if p.checkFields(&w, language, rid) {
			gps, pres := p.dbo.receiverFrequncy(rid)
			res := make(map[string]int)
			res["errcode"] = 0
			res["tiredata"] = pres
			res["gps"] = gps

			buf, _ := json.Marshal(res)
			w.Write(buf)
		}
	}
}

// 修改数据上传频率
func (p *HttpListener) ReceiverSetUploadFrequncy(w http.ResponseWriter, req *http.Request) {
	if language, _, ok := p.commonCheck(&w, req); ok {
		req.Header.Set("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept")
		w.Header().Add("Access-Control-Allow-Methods", "POST,GET,OPTIONS,DELETE")

		req.ParseForm()

		rid := req.FormValue("rid")
		tiredata := req.FormValue("tiredata")
		gps := req.FormValue("gps")

		if p.checkFields(&w, language, rid, tiredata, gps) {
			var iTireData, iGPS int
			var err error
			var sResult string

			iTireData, err = strconv.Atoi(tiredata)
			if err == nil {
				iGPS, err = strconv.Atoi(gps)
			}
			if err != nil {
				sResult = p.makeResultStr(1009, "参数错误", language)
				w.Write([]byte(sResult))
				return
			}
			if p.dbo.receiverType(rid) < 0 {
				sResult = p.makeResultStr(1004, "未找到该设备", language)
				w.Write([]byte(sResult))
				return
			}

			postData := make(map[string]interface{})
			postData["rid"] = rid
			postData["tiredata"] = iTireData
			postData["gps"] = iGPS

			buf, _ := json.Marshal(postData)

			buf, _ = p.Post(p.cfg.ReceiverdURL+"/receiver/setfrequncy", "", buf)
			w.Write(buf)
		}
	}
}

// 设置设备休眠
func (p *HttpListener) ReceiverSetDeviceSleep(w http.ResponseWriter, req *http.Request) {
	if language, _, ok := p.commonCheck(&w, req); ok {
		req.Header.Set("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept")
		w.Header().Add("Access-Control-Allow-Methods", "POST,GET,OPTIONS,DELETE")

		req.ParseForm()

		rid := req.FormValue("rid")
		deviceSleep := req.FormValue("devicesleep")

		if p.checkFields(&w, language, rid, deviceSleep) {
			var iDeviceSleep int
			var err error
			var sResult string

			iDeviceSleep, err = strconv.Atoi(deviceSleep)
			if err != nil {
				sResult = p.makeResultStr(1009, "参数错误", language)
				w.Write([]byte(sResult))
				return
			}
			if iDeviceSleep > 1 {
				iDeviceSleep = 1
			}
			if p.dbo.receiverType(rid) < 0 {
				sResult = p.makeResultStr(1004, "未找到该设备", language)
				w.Write([]byte(sResult))
				return
			}

			postData := make(map[string]interface{})
			postData["rid"] = rid
			postData["devicesleep"] = iDeviceSleep
			buf, _ := json.Marshal(postData)
			buf, _ = p.Post(p.cfg.ReceiverdURL+"/receiver/setdevicesleep", "", buf)
			w.Write(buf)
		}
	}
}

type DeviceScreenParamT struct {
	Rid         string
	Voice       int
	TempUnit    int
	PresUnit    int
	VehicleType int
}

func (p *HttpListener) ReceiverSetScreen(w http.ResponseWriter, req *http.Request) {
	if language, _, ok := p.commonCheck(&w, req); ok {
		req.Header.Set("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept")
		w.Header().Add("Access-Control-Allow-Methods", "POST,GET,OPTIONS,DELETE")

		var dsp DeviceScreenParamT
		var sResult string
		buf, err := p.readBody(req)
		if err == nil {
			err = json.Unmarshal(buf, &dsp)
			if err == nil {
				if dsp.Rid == "" || (dsp.Voice == 0 && dsp.TempUnit == 0 && dsp.PresUnit == 0 && dsp.VehicleType == 0) {
					err = errors.New("参数不正确")
				}
			}
		}
		if err != nil {
			sResult = p.makeResultStr(1009, "参数错误", language)
			w.Write([]byte(sResult))
			return
		}

		if p.dbo.receiverType(dsp.Rid) < 0 {
			sResult = p.makeResultStr(1004, "未找到该设备", language)
			w.Write([]byte(sResult))
			return
		}

		err = p.dbo.receiverSetScreen(&dsp)
		if err != nil {
			sResult = p.makeResultStr2(1101, "操作失败", err.Error(), language)
		} else {
			sResult = p.makeResultStr(0, "", language)
		}
		w.Write([]byte(sResult))
	}
}

func (p *HttpListener) ReceiverRemoteUpdate(w http.ResponseWriter, req *http.Request) {
	if language, userid, ok := p.commonCheck(&w, req); ok {
		//只有系统管理员才能够操作
		if p.checkUserType(&w, language, userid) {
			req.ParseForm()

			rids := req.FormValue("rids")
			fileUrl := req.FormValue("url")
			productor := req.FormValue("productor")
			firmwarever := req.FormValue("firmwarever")
			softwarever := req.FormValue("softwarever")

			var sErr string

			if p.checkFields(&w, language, rids, fileUrl, productor, firmwarever, softwarever) {
				ridSlice := strings.Split(rids, ",")
				p.dbo.receiverRemoteUpdate(fileUrl, productor, firmwarever, softwarever, ridSlice)

				sErr = p.makeResultStr(0, "", language)
				w.Write([]byte(sErr))
			}
		}
	}
}

// 接收器详情
func (p *HttpListener) ReceiverDetail(w http.ResponseWriter, req *http.Request) {
	if language, userid, ok := p.commonCheck(&w, req); ok {
		//只有系统管理员才能够操作
		if p.checkUserType(&w, language, userid) {
			req.ParseForm()

			rid := req.FormValue("rid")

			if p.checkFields(&w, language, rid) {
				detail, err := p.dbo.receiverDetail(rid)
				if err != nil {
					sErr := p.makeResultStr(1101, err.Error(), language)
					w.Write([]byte(sErr))
				} else {
					var ret map[string]interface{} = make(map[string]interface{})
					ret["errcode"] = 0
					ret["data"] = detail
					buf, _ := json.Marshal(ret)
					w.Write(buf)
				}

			}
		}
	}
}

// 接收器最新位置
func (p *HttpListener) ReceiverLocation(w http.ResponseWriter, req *http.Request) {
	if language, _, ok := p.commonCheck(&w, req); ok {
		req.ParseForm()

		rid := req.FormValue("rid")
		mapType := req.FormValue("type")
		if mapType == "" {
			mapType = GpsWGS84 //默认为原始坐标
		}

		if p.checkFields(&w, language, rid) {
			lat, lng, err := p.dbo.receiverLocation(rid, mapType)
			if err != nil {
				sErr := p.makeResultStr2(1027, "获取定位信息失败", err.Error(), language)
				w.Write([]byte(sErr))
			} else {
				var ret map[string]interface{} = make(map[string]interface{})
				ret["errcode"] = 0
				ret["lat"] = lat
				ret["lng"] = lng
				buf, _ := json.Marshal(ret)
				w.Write(buf)
			}
		}
	}
}

// 轨迹日期查询
func (p *HttpListener) ReceiverTrackDates(w http.ResponseWriter, req *http.Request) {
	if language, _, ok := p.commonCheck(&w, req); ok {
		req.ParseForm()

		rid := req.FormValue("rid")
		month := req.FormValue("month")

		if p.checkFields(&w, language, rid, month) {
			m, _ := strconv.Atoi(month)
			days := p.dbo.receiverTrackDates(rid, m/100, m%100)

			var ret map[string]interface{} = make(map[string]interface{})
			ret["errcode"] = 0
			ret["days"] = days
			buf, _ := json.Marshal(ret)
			w.Write(buf)
		}
	}
}

// 设置接收器的固定胎温胎压
func (p *HttpListener) ReceiverSetFixTempAndPres(w http.ResponseWriter, req *http.Request) {
	if language, userId, ok := p.commonCheck(&w, req); ok {
		req.ParseForm()

		rid := req.FormValue("rid")
		temp := req.FormValue("temp")
		press := req.FormValue("press")

		if p.checkFields(&w, language, rid, temp, press) {
			t := 0
			pr := 0.0
			var err error

			t, err = strconv.Atoi(temp)
			if err == nil {
				pr, err = strconv.ParseFloat(press, 32)
			}
			if err != nil {
				p.wrongParameter(&w, err, language)
				return
			}

			err = p.dbo.receiverSetFixTempAndPres(userId, rid, t, pr)
			res := ""
			if err == nil {
				res = p.makeResultStr(0, "", language)
			} else {
				res = p.makeResultStr2(1101, "设置失败", err.Error(), language)
			}

			w.Write([]byte(res))
		}
	}
}

// 查询接收器的固定胎温胎压
func (p *HttpListener) ReceiverFixTempAndPres(w http.ResponseWriter, req *http.Request) {
	if language, userId, ok := p.commonCheck(&w, req); ok {
		req.ParseForm()

		rid := req.FormValue("rid")

		if p.checkFields(&w, language, rid) {
			temp, press, err := p.dbo.receiverFixTempAndPres(userId, rid)
			if err == nil {
				var ret map[string]interface{} = make(map[string]interface{})
				ret["errcode"] = 0
				ret["data"] = bson.M{"temp": temp, "press": press}
				buf, _ := json.Marshal(ret)
				w.Write(buf)

			} else {
				res := p.makeResultStr2(1101, "设置失败", err.Error(), language)
				w.Write([]byte(res))
			}
		}
	}
}

// 公司管理----------------------------------------------------------------------------
// 检查用户权限
func (p *HttpListener) checkUserType(w *http.ResponseWriter, language string, userid string) bool {
	userType := p.dbo.userType(userid)
	if userType != UserTypeSystemUser {
		sErr := p.makeResultStr(1014, "无此权限", language)
		(*w).Write([]byte(sErr))
		return false
	}
	return true
}

// 公司列表
func (p *HttpListener) CompanyList(w http.ResponseWriter, req *http.Request) {
	if language, userid, ok := p.commonCheck(&w, req); ok {
		if p.checkUserType(&w, language, userid) {
			res := p.dbo.companyList()
			var ret map[string]interface{} = make(map[string]interface{})
			ret["errcode"] = 0
			ret["companies"] = res
			buf, _ := json.Marshal(ret)
			zLog(nil, "CompanyList success......")
			w.Write(buf)
		}
	}
}

// 添加公司
func (p *HttpListener) CompanyAdd(w http.ResponseWriter, req *http.Request) {
	if language, userid, ok := p.commonCheck(&w, req); ok {
		if p.checkUserType(&w, language, userid) {
			req.ParseForm()
			name := req.FormValue("name")
			manager := req.FormValue("manager")
			phone := req.FormValue("phone")
			email := req.FormValue("email")
			logo := req.FormValue("logo")

			if p.checkFields(&w, language, name) {
				cid, err := p.dbo.companyAdd(name, manager, phone, email, logo)
				if err != nil {
					sErr := p.makeResultStr(1101, err.Error(), language)
					w.Write([]byte(sErr))
				} else {
					var ret map[string]interface{} = make(map[string]interface{})
					ret["errcode"] = 0
					ret["cid"] = cid
					buf, _ := json.Marshal(ret)
					w.Write(buf)
				}
			}
		}
	}
}

// 修改公司信息
func (p *HttpListener) CompanyModify(w http.ResponseWriter, req *http.Request) {
	if language, userid, ok := p.commonCheck(&w, req); ok {
		if p.checkUserType(&w, language, userid) {
			req.ParseForm()
			cid := req.FormValue("cid")
			name := req.FormValue("name")
			manager := req.FormValue("manager")
			phone := req.FormValue("phone")
			email := req.FormValue("email")
			logo := req.FormValue("logo")

			if p.checkFields(&w, language, cid) {
				var sErr string
				iCid, err := strconv.Atoi(cid)
				if err != nil {
					sErr = p.makeResultStr(1009, "参数错误", language)
					w.Write([]byte(sErr))
					return
				}
				err = p.dbo.companyModify(iCid, name, manager, phone, email, logo)
				if err != nil {
					sErr = p.makeResultStr(1101, err.Error(), language)
				} else {
					sErr = p.makeResultStr(0, "", language)
				}
				w.Write([]byte(sErr))
			}
		}
	}
}

// 删除公司
func (p *HttpListener) CompanyDelete(w http.ResponseWriter, req *http.Request) {
	if language, userid, ok := p.commonCheck(&w, req); ok {
		if p.checkUserType(&w, language, userid) {
			req.ParseForm()

			cid := req.FormValue("cid")
			if p.checkFields(&w, language, cid) {
				var sErr string
				iCid, err := strconv.Atoi(cid)
				if err != nil {
					sErr = p.makeResultStr(1009, "参数错误", language)
					w.Write([]byte(sErr))
					return
				}

				err = p.dbo.companyDelete(iCid)
				if err != nil {
					sErr = p.makeResultStr(1101, err.Error(), language)
				} else {
					sErr = p.makeResultStr(0, "", language)
				}
				w.Write([]byte(sErr))
			}
		}
	}
}

// 公司概况
func (p *HttpListener) CompanyBrief(w http.ResponseWriter, req *http.Request) {
	if language, _, ok := p.commonCheck(&w, req); ok {
		req.ParseForm()
		cid := req.FormValue("cid")
		tid := req.FormValue("tid")
		d := req.FormValue("date")

		if p.checkFields(&w, language, cid) {
			var sErr string
			var iCid, iDate int
			var err error

			iCid, err = strconv.Atoi(cid)
			if err != nil {
				sErr = p.makeResultStr(1009, "参数错误", language)
				w.Write([]byte(sErr))
				return
			}
			iDate, err = strconv.Atoi(d)
			if err != nil {
				iDate = 0
			}

			ret, err := p.dbo.companyBrief(iCid, tid, iDate)
			if err != nil {
				sErr = p.makeResultStr(1101, err.Error(), language)
				w.Write([]byte(sErr))
				return
			}
			res := make(map[string]interface{})
			res["errcode"] = 0
			res["data"] = ret

			buf, _ := json.Marshal(res)
			w.Write(buf)
		}
	}
}

func (p *HttpListener) CompanySubTeam(w http.ResponseWriter, req *http.Request) {
	if language, _, ok := p.commonCheck(&w, req); ok {

		req.ParseForm()
		cid := req.FormValue("cid")
		tid := req.FormValue("tid")

		if p.checkFields(&w, language, cid) {
			var sErr string
			var iCid int
			var err error

			iCid, err = strconv.Atoi(cid)
			if err != nil {
				sErr = p.makeResultStr(1009, "参数错误", language)
				w.Write([]byte(sErr))
				return
			}

			ret, err := p.dbo.companySubTeam(iCid, tid)
			if err != nil {
				sErr = p.makeResultStr(1101, err.Error(), language)
				w.Write([]byte(sErr))
				return
			}
			res := make(map[string]interface{})
			res["errcode"] = 0
			res["cid"] = iCid
			res["teams"] = ret

			buf, _ := json.Marshal(res)
			w.Write(buf)
		}
	}
}

// 司机管理----------------------------------------------------------------------------
// 司机管理信息列表
func (p *HttpListener) DriverNameList(w http.ResponseWriter, req *http.Request) {
	if language, _, ok := p.commonCheck(&w, req); ok {
		req.ParseForm()
		cid := req.FormValue("cid")
		tid := req.FormValue("tid") //tid允许为空

		var iCid int
		var err error
		var sErr string

		iCid, err = strconv.Atoi(cid)
		if err != nil {
			sErr = p.makeResultStr(1009, "参数错误", language)
			w.Write([]byte(sErr))
			return
		}

		drivers := p.dbo.driverNameList(iCid, tid)
		res := make(map[string]interface{})
		res["errcode"] = 0
		res["drivers"] = drivers

		buf, _ := json.Marshal(res)
		w.Write(buf)
	}
}

// 司机列表
func (p *HttpListener) DriverList(w http.ResponseWriter, req *http.Request) {
	if language, _, ok := p.commonCheck(&w, req); ok {
		req.ParseForm()
		cid := req.FormValue("cid")
		tid := req.FormValue("tid") //tid允许为空
		name := req.FormValue("name")
		page := req.FormValue("page")

		var iCid, iPage int
		var err error
		var sErr string

		iCid, err = strconv.Atoi(cid)
		if err != nil {
			sErr = p.makeResultStr(1009, "参数错误", language)
			w.Write([]byte(sErr))
			return
		}
		iPage, err = strconv.Atoi(page)
		if err != nil {
			iPage = 0
		}

		count, drivers := p.dbo.driverList(iCid, tid, name, iPage)
		res := make(map[string]interface{})
		res["errcode"] = 0
		res["total"] = count
		res["drivers"] = drivers

		buf, _ := json.Marshal(res)
		w.Write(buf)
	}
}

// 添加司机
func (p *HttpListener) DriverAdd(w http.ResponseWriter, req *http.Request) {
	if language, _, ok := p.commonCheck(&w, req); ok {
		req.ParseForm()
		cid := req.FormValue("cid")
		tid := req.FormValue("tid")
		name := req.FormValue("name")
		idcard := req.FormValue("idcard")
		gender := req.FormValue("gender")
		if gender == "" {
			gender = "-1"
		}
		birthday := req.FormValue("birthday")
		if birthday == "" {
			birthday = "0"
		}
		drivingage := req.FormValue("drivingage")
		if drivingage == "" {
			drivingage = "0"
		}
		phone := req.FormValue("phone")
		license := req.FormValue("license")
		photo := req.FormValue("photo")

		var err error
		var sErr string
		var iCid, iGender, iBirthday, iDrivingAge int
		iCid, err = strconv.Atoi(cid)

		if err == nil {
			if iCid == 0 {
				err = errors.New("公司ID不允许为0")
			} else {
				iGender, err = strconv.Atoi(gender)
				if err == nil {
					iBirthday, err = strconv.Atoi(birthday)
					if err == nil {
						iDrivingAge, err = strconv.Atoi(drivingage)
					}
				}
			}
		}
		if err != nil {
			sErr = p.makeResultStr(1009, "参数错误", language)
			w.Write([]byte(sErr))
			return
		}

		if p.checkFields(&w, language, cid, name, idcard) {
			driverAdd := DriverAddT{
				DriverID:   bson.NewObjectId().Hex(),
				Name:       name,
				IdCard:     idcard,
				Cid:        iCid,
				Tid:        tid,
				Gender:     iGender,
				Birthday:   iBirthday,
				DrivingAge: iDrivingAge,
				Phone:      phone,
				License:    license,
				Photo:      photo,
			}
			err = p.dbo.driverAdd(&driverAdd)
			if err != nil {
				sErr = p.makeResultStr(1016, "已经存在该司机信息", language)
			} else {
				sErr = p.makeResultStr(0, "", language)
			}
			w.Write([]byte(sErr))
		}
	}
}

// 修改司机
func (p *HttpListener) DriverEdit(w http.ResponseWriter, req *http.Request) {
	if language, _, ok := p.commonCheck(&w, req); ok {
		req.ParseForm()
		did := req.FormValue("driverid")
		cid := req.FormValue("cid")
		tid := req.FormValue("tid")
		name := req.FormValue("name")
		idcard := req.FormValue("idcard")
		gender := req.FormValue("gender")
		if gender == "" {
			gender = "-1"
		}
		birthday := req.FormValue("birthday")
		if birthday == "" {
			birthday = "0"
		}
		drivingage := req.FormValue("drivingage")
		if drivingage == "" {
			drivingage = "0"
		}
		phone := req.FormValue("phone")
		license := req.FormValue("license")
		photo := req.FormValue("photo")

		var err error
		var sErr string
		var iCid, iGender, iBirthday, iDrivingAge int
		iCid, err = strconv.Atoi(cid)
		if err == nil {
			iGender, err = strconv.Atoi(gender)
			if err == nil {
				iBirthday, err = strconv.Atoi(birthday)
				if err == nil {
					iDrivingAge, err = strconv.Atoi(drivingage)
				}
			}
		}
		if err != nil {
			sErr = p.makeResultStr(1009, "参数错误", language)
			w.Write([]byte(sErr))
			return
		}

		if p.checkFields(&w, language, did, cid, name, idcard) {
			driverAdd := DriverAddT{
				DriverID:   did,
				Name:       name,
				IdCard:     idcard,
				Cid:        iCid,
				Tid:        tid,
				Gender:     iGender,
				Birthday:   iBirthday,
				DrivingAge: iDrivingAge,
				Phone:      phone,
				License:    license,
				Photo:      photo,
			}
			err = p.dbo.driverEdit(&driverAdd)
			if err != nil {
				sErr = p.makeResultStr(1017, "修改司机信息时出错", language)
				sErr = sErr + ":" + err.Error()
			} else {
				sErr = p.makeResultStr(0, "", language)
			}
			w.Write([]byte(sErr))
		}
	}
}

// 删除司机
func (p *HttpListener) DriverDelete(w http.ResponseWriter, req *http.Request) {
	if language, _, ok := p.commonCheck(&w, req); ok {
		req.ParseForm()
		did := req.FormValue("driverid")

		var sErr string

		if p.checkFields(&w, language, did) {
			p.dbo.driverDelete(did)
			sErr = p.makeResultStr(0, "", language)
			w.Write([]byte(sErr))
		}
	}
}

// 车队管理----------------------------------------------------------------------------
// 车队列表
// TODO::这个函数的代码逻辑有时间要好好整理一下
func (p *HttpListener) TeamList(w http.ResponseWriter, req *http.Request) {
	if language, userid, ok := p.commonCheck(&w, req); ok {
		req.ParseForm()
		cid := req.FormValue("cid")
		tid := req.FormValue("tid") //tid允许为空
		needcid := req.FormValue("needcid")

		var iCid, iNeedCid int
		var err error
		iCid, err = strconv.Atoi(cid)
		if err != nil {
			sErr := p.makeResultStr(1009, "参数错误", language)
			w.Write([]byte(sErr))
			return
		}
		iNeedCid, err = strconv.Atoi(needcid)
		if err != nil {
			iNeedCid = 0
		}

		teams := make([]map[string]interface{}, 0)

		//首先找出第一条结点的数据
		userType := p.dbo.userType(userid)
		if userType == UserTypeSystemUser && iCid == 0 {
			//系统管理员，列出所有的公司及车队
			teams = append(teams, p.dbo.userConcernedTeam(userid))

			companies := p.dbo.companyList()
			for _, v := range companies {
				company := map[string]interface{}{"name": v.Name, "cid": v.Cid, "tid": "", "teams": []map[string]interface{}{}}
				teams = append(teams, company)
			}
		} else {
			//只列出本公司或本车队的车队
			var name string
			company := map[string]interface{}{"teams": []map[string]interface{}{}}
			company["tid"] = tid
			company["cid"] = iCid
			if tid != "" {
				name = p.dbo.getTeamName(tid)
			} else if iCid != 0 {
				name = p.dbo.getCompanyName(iCid)
			} else {
				sErr := p.makeResultStr(1009, "参数错误", language)
				w.Write([]byte(sErr))
				return
			}
			company["name"] = name
			teams = append(teams, company)
		}

		var team map[string]interface{}
		var tempCid int
		var tempTid string

		for i := 0; i < len(teams); i++ {
			team = teams[i]
			if _, ok := team["tid"]; ok {
				tempTid = team["tid"].(string)
			}
			if _, ok := team["cid"]; ok {
				tempCid = team["cid"].(int)
			}

			if tempTid != "" {
				team["teams"] = p.dbo.teamListByTid(tempTid, iNeedCid)
			} else if tempCid != -1 {
				team["teams"] = p.dbo.teamListByCid(tempCid, iNeedCid)
			}
		}

		res := make(map[string]interface{})
		res["errcode"] = 0
		res["teams"] = teams

		buf, _ := json.Marshal(res)
		w.Write(buf)
	}
}

/*
//找父车队
func (p *HttpListener) findParentTeam(teams []map[string]interface{}, pid string) *map[string]interface{} {
	if len(teams) == 0 {
		return nil
	}

	var pt *map[string]interface{}
	var sTid string

	for _, v := range teams {
		sTid = v["tid"].(string)
		if sTid == pid {
			return &v
		} else if v["teams"] != nil {
			subTeam := v["teams"].([]map[string]interface{})
			pt = p.findParentTeam(subTeam, pid)
			if pt != nil {
				return pt
			}
		}
	}
	return nil
}
*/

// 添加车队
func (p *HttpListener) TeamAdd(w http.ResponseWriter, req *http.Request) {
	if language, _, ok := p.commonCheck(&w, req); ok {
		req.ParseForm()
		cid := req.FormValue("cid")
		pid := req.FormValue("pid")
		name := req.FormValue("name")
		contact := req.FormValue("contact")
		phone := req.FormValue("phone")
		workflow := req.FormValue("workflow")
		iCid, err := strconv.Atoi(cid)
		if err != nil {
			sErr := p.makeResultStr(1009, "参数错误", language)
			w.Write([]byte(sErr))
			return
		}

		if p.checkFields(&w, language, cid, name) {
			tid, err := p.dbo.addTeam(iCid, pid, name, contact, phone, workflow)
			if err != nil {
				sErr := p.makeResultStr(1010, "已经存在相同的车队名", language)
				w.Write([]byte(sErr))
			} else {
				res := make(map[string]interface{})
				res["errcode"] = 0
				res["tid"] = tid
				buf, _ := json.Marshal(res)
				w.Write(buf)
			}
		}
	}
}

// 编辑车队
func (p *HttpListener) TeamEdit(w http.ResponseWriter, req *http.Request) {
	if language, _, ok := p.commonCheck(&w, req); ok {
		req.ParseForm()
		tid := req.FormValue("tid")
		name := req.FormValue("name")
		contact := req.FormValue("contact")
		phone := req.FormValue("phone")
		workflow := req.FormValue("workflow")

		if p.checkFields(&w, language, tid, name) {
			err := p.dbo.editTeam(tid, name, contact, phone, workflow)
			if err != nil {
				sErr := p.makeResultStr(1010, err.Error(), language)
				w.Write([]byte(sErr))
			} else {
				res := make(map[string]interface{})
				res["errcode"] = 0
				buf, _ := json.Marshal(res)
				w.Write(buf)
			}
		}
	}
}

// 删除车队
func (p *HttpListener) TeamDelete(w http.ResponseWriter, req *http.Request) {
	if language, _, ok := p.commonCheck(&w, req); ok {
		req.ParseForm()
		tid := req.FormValue("tid")

		if p.checkFields(&w, language, tid) {
			p.dbo.deleteTeam(tid)
			sErr := p.makeResultStr(0, "", language)
			w.Write([]byte(sErr))
		}
	}
}

// 车辆管理----------------------------------------------------------------------------
// 车辆品牌列表
func (p *HttpListener) VehicleBrandList(w http.ResponseWriter, req *http.Request) {
	if language, _, ok := p.commonCheck(&w, req); ok {
		req.ParseForm()
		cid := req.FormValue("cid")
		if p.checkFields(&w, language, cid) {
			iCid, err := strconv.Atoi(cid)
			if err != nil {
				sErr := p.makeResultStr(1009, "参数错误", language)
				w.Write([]byte(sErr))
				return
			}

			vl := p.dbo.vehicleBrandList(iCid)
			res := make(map[string]interface{})
			res["errcode"] = 0
			res["vehiclebrands"] = vl
			buf, _ := json.Marshal(res)
			w.Write(buf)
		}
	}
}

// 添加车辆品牌
func (p *HttpListener) VehicleBrandAdd(w http.ResponseWriter, req *http.Request) {
	if language, _, ok := p.commonCheck(&w, req); ok {
		req.ParseForm()
		cid := req.FormValue("cid")
		name := req.FormValue("name")
		if p.checkFields(&w, language, cid, name) {
			iCid, err := strconv.Atoi(cid)
			if err != nil {
				sErr := p.makeResultStr(1009, "参数错误", language)
				w.Write([]byte(sErr))
				return
			}

			id, err := p.dbo.vehicleBrandAdd(iCid, name)
			if err != nil {
				sErr := p.makeResultStr2(1018, "添加车辆品牌失败", err.Error(), language)
				w.Write([]byte(sErr))
			} else {
				res := make(map[string]interface{})
				res["errcode"] = 0
				res["vbid"] = id
				buf, _ := json.Marshal(res)
				w.Write(buf)
			}
		}
	}
}

// 修改车辆品牌
func (p *HttpListener) VehicleBrandEdit(w http.ResponseWriter, req *http.Request) {
	if language, _, ok := p.commonCheck(&w, req); ok {
		req.ParseForm()
		id := req.FormValue("vbid")
		name := req.FormValue("name")

		if p.checkFields(&w, language, id, name) {
			err := p.dbo.vehicleBrandEdit(id, name)
			var sErr string
			if err != nil {
				sErr = p.makeResultStr2(1019, "修改车辆品牌失败", err.Error(), language)
			} else {
				sErr = p.makeResultStr(0, "", language)
			}
			w.Write([]byte(sErr))
		}
	}
}

// 删除车辆品牌
func (p *HttpListener) VehicleBrandDelete(w http.ResponseWriter, req *http.Request) {
	if language, _, ok := p.commonCheck(&w, req); ok {
		req.ParseForm()
		id := req.FormValue("vbid")

		if p.checkFields(&w, language, id) {
			err := p.dbo.vehicleBrandDelete(id)
			var sErr string
			if err != nil {
				sErr = p.makeResultStr2(1020, "删除车辆品牌失败", err.Error(), language)
			} else {
				sErr = p.makeResultStr(0, "", language)
			}
			w.Write([]byte(sErr))
		}
	}
}

// 车辆型号列表
func (p *HttpListener) VehicleModelList(w http.ResponseWriter, req *http.Request) {
	if language, _, ok := p.commonCheck(&w, req); ok {
		req.ParseForm()

		vbid := req.FormValue("vbid")
		if p.checkFields(&w, language, vbid) {
			vl := p.dbo.vehicleModelList(vbid)
			res := make(map[string]interface{})
			res["errcode"] = 0
			res["vehiclemodels"] = vl
			buf, _ := json.Marshal(res)
			w.Write(buf)
		}
	}
}

// 添加车辆型号
func (p *HttpListener) VehicleModelAdd(w http.ResponseWriter, req *http.Request) {
	if language, _, ok := p.commonCheck(&w, req); ok {
		req.ParseForm()
		vbid := req.FormValue("vbid")
		name := req.FormValue("name")
		model := req.FormValue("model")
		if p.checkFields(&w, language, vbid, name, model) {
			id, err := p.dbo.vehicleModelAdd(vbid, name, model)
			if err != nil {
				sErr := p.makeResultStr2(1021, "添加车辆型号失败", err.Error(), language)
				w.Write([]byte(sErr))
			} else {
				res := make(map[string]interface{})
				res["errcode"] = 0
				res["vmid"] = id
				buf, _ := json.Marshal(res)
				w.Write(buf)
			}
		}
	}
}

// 修改车辆型号
func (p *HttpListener) VehicleModelEdit(w http.ResponseWriter, req *http.Request) {
	if language, _, ok := p.commonCheck(&w, req); ok {
		req.ParseForm()
		vbid := req.FormValue("vbid")
		vmid := req.FormValue("vmid")
		model := req.FormValue("model")

		if p.checkFields(&w, language, vbid, vmid, model) {
			err := p.dbo.vehicleModelEdit(vbid, vmid, model)
			var sErr string
			if err != nil {
				sErr = p.makeResultStr2(1022, "修改车辆型号失败", err.Error(), language)
			} else {
				sErr = p.makeResultStr(0, "", language)
			}
			w.Write([]byte(sErr))
		}
	}
}

// 删除车辆型号
func (p *HttpListener) VehicleModelDelete(w http.ResponseWriter, req *http.Request) {
	if language, _, ok := p.commonCheck(&w, req); ok {
		req.ParseForm()
		id := req.FormValue("vmid")

		if p.checkFields(&w, language, id) {
			err := p.dbo.vehicleModelDelete(id)
			var sErr string
			if err != nil {
				sErr = p.makeResultStr2(1023, "删除车辆型号失败", err.Error(), language)
			} else {
				sErr = p.makeResultStr(0, "", language)
			}
			w.Write([]byte(sErr))
		}
	}
}

// 车辆列表
func (p *HttpListener) VehicleList(w http.ResponseWriter, req *http.Request) {
	if language, userid, ok := p.commonCheck(&w, req); ok {
		req.ParseForm()
		cid := req.FormValue("cid")
		tid := req.FormValue("tid")
		content := req.FormValue("content")
		iCid, err := strconv.Atoi(cid)
		if err != nil {
			sErr := p.makeResultStr(1009, "参数错误", language)
			w.Write([]byte(sErr))
			return
		}

		if p.dbo.userType(userid) != UserTypeSystemUser && iCid == 0 {
			sErr := p.makeResultStr(1014, "无此权限", language)
			w.Write([]byte(sErr))
			return
		}

		page := req.FormValue("page")
		iPage, err := strconv.Atoi(page)
		if err != nil {
			iPage = 0
		}

		if p.checkFields(&w, language, cid) {
			total, vl := p.dbo.vehicleList( /*userid, */ iCid, tid, content, iPage)
			res := make(map[string]interface{})
			res["errcode"] = 0
			res["total"] = total
			res["vehicles"] = vl
			buf, _ := json.Marshal(res)
			w.Write(buf)
		}
	}
}

// 车辆列表2
func (p *HttpListener) VehicleList2(w http.ResponseWriter, req *http.Request) {
	if language, userid, ok := p.commonCheck(&w, req); ok {
		req.ParseForm()
		cid := req.FormValue("cid")
		tid := req.FormValue("tid")
		content := req.FormValue("content")
		sort := req.FormValue("sort")
		iCid, err := strconv.Atoi(cid)
		if err != nil {

			p.wrongParameter(&w, err, language)
			return
		}
		page := req.FormValue("page")
		iPage, err := strconv.Atoi(page)
		if err != nil {
			iPage = 0
		}

		if p.checkFields(&w, language, cid) {
			total, vl := p.dbo.vehicleList2(userid, iCid, tid, content, sort, iPage)
			res := make(map[string]interface{})
			res["errcode"] = 0
			res["total"] = total
			res["vehicles"] = vl
			buf, _ := json.Marshal(res)
			w.Write(buf)
		}
	}
}

/*
//添加车辆
func (p *HttpListener) VehicleAdd(w http.ResponseWriter, req *http.Request) {
	if language, _, ok := p.commonCheck(&w, req); ok {
		req.ParseForm()
		cid := req.FormValue("cid")
		tid := req.FormValue("tid")
		plate := req.FormValue("plate")
		frame := req.FormValue("frame")
		sType := req.FormValue("type")
		rid := req.FormValue("rid")
		enginetype := req.FormValue("enginetype")

		var iCid, iType, iEngineType int
		var err error

		iCid, err = strconv.Atoi(cid)
		if err == nil {
			iType, err = strconv.Atoi(sType)
			if err == nil {
				iEngineType, _ = strconv.Atoi(enginetype)
			}
		}
		if err != nil || (plate == "" && frame == "") || !((iType >= 1 && iType <= 6) || (iType >= 101 && iType <= 105)) {
			sErr := p.makeResultStr(1009, "参数错误", language)
			w.Write([]byte(sErr))
			return
		}

		if p.checkFields(&w, language, cid) {
			//判断是否存在设备号
			if rid != "" {
				if p.dbo.receiverType(rid) == -1 {
					sErr := p.makeResultStr(1008, "您没有该设备", language)
					w.Write([]byte(sErr))
					return
				}
			}

			vehicle := VehicleDBT{}
			vehicle.Vid = bson.NewObjectId().Hex()
			vehicle.Cid = iCid
			vehicle.Tid = tid
			vehicle.Driver = strings.TrimSpace(req.FormValue("driver"))
			vehicle.DriverPhone = strings.TrimSpace(req.FormValue("driverphone"))
			vehicle.Plate = strings.TrimSpace(plate)
			vehicle.Frame = strings.TrimSpace(frame)
			vehicle.Type = iType
			vehicle.Rid = rid
			vehicle.EngineType = iEngineType

			err := p.dbo.vehicleAdd(&vehicle)
			if err != nil {
				sErr := p.makeResultStr(1100, err.Error(), language)
				w.Write([]byte(sErr))
			} else {
				res := make(map[string]interface{})
				res["errcode"] = 0
				res["vid"] = vehicle.Vid
				buf, _ := json.Marshal(res)
				w.Write(buf)
			}
		}
	}
}
*/
//添加车辆
func (p *HttpListener) VehicleAdd2(w http.ResponseWriter, req *http.Request) {
	if language, _, ok := p.commonCheck(&w, req); ok {
		req.ParseForm()
		cid := req.FormValue("cid")
		tid := req.FormValue("tid")
		plate := req.FormValue("plate")
		frame := req.FormValue("frame")
		sType := req.FormValue("type")
		rid := req.FormValue("rid")
		dom := req.FormValue("dom")
		dop := req.FormValue("dop")
		payload := req.FormValue("payload")
		realpayload := req.FormValue("realpayload")
		drivers := req.FormValue("drivers")
		brandid := req.FormValue("brandid")
		modelid := req.FormValue("modelid")
		initmileage := req.FormValue("initmileage")
		enginetype := req.FormValue("enginetype")

		var iCid, iType, iDom, iDop, iPayload, iRealPayload, iInitMileage, iEngineType int
		var err error
		var sErr string

		iCid, err = strconv.Atoi(cid)
		if err == nil {
			iType, err = p.checkVehicleType(sType)
			if err == nil {
				iDom, _ = strconv.Atoi(dom)
				iDop, _ = strconv.Atoi(dop)
				iPayload, _ = strconv.Atoi(payload)
				iRealPayload, _ = strconv.Atoi(realpayload)
				iInitMileage, _ = strconv.Atoi(initmileage)
				iEngineType, _ = strconv.Atoi(enginetype)
			} else {
				p.wrongParameter(&w, err, language)
				return
			}
		}

		if err != nil || (plate == "" && frame == "") {
			p.wrongParameter(&w, nil, language)

			return
		}

		if p.checkFields(&w, language, cid) {
			//判断是否存在设备号
			if rid != "" {
				if !p.dbo.haveReceiver(iCid, tid, rid) {
					sErr = p.makeResultStr(1008, "您没有该设备", language)
					w.Write([]byte(sErr))
					return
				}
			}

			vehicle := VehicleInfoDBT{}
			vehicle.Vid = bson.NewObjectId().Hex()
			vehicle.Cid = iCid
			vehicle.Tid = tid
			if tid != "" {
				vehicle.Tids = p.dbo.getTeamParents(tid)
			}
			vehicle.Plate = strings.TrimSpace(plate)
			vehicle.Frame = strings.TrimSpace(frame)
			vehicle.Type = iType
			vehicle.Rid = rid
			vehicle.BrandID = brandid
			vehicle.ModelID = modelid
			vehicle.Dom = iDom
			vehicle.Dop = iDop
			vehicle.Payload = iPayload
			vehicle.RealPayload = iRealPayload
			vehicle.DriverIDs = strings.Split(drivers, ",")
			vehicle.InitMileage = iInitMileage
			vehicle.EngineType = iEngineType

			err := p.dbo.vehicleAdd2(&vehicle)
			if err != nil {
				sErr = p.makeResultStr2(1025, "添加车辆失败", err.Error(), language)
				w.Write([]byte(sErr))
			} else {
				res := make(map[string]interface{})
				res["errcode"] = 0
				res["vid"] = vehicle.Vid
				buf, _ := json.Marshal(res)
				w.Write(buf)
			}
		}
	}
}

/*
//修改车辆
func (p *HttpListener) VehicleEdit(w http.ResponseWriter, req *http.Request) {
	if language, _, ok := p.commonCheck(&w, req); ok {
		req.ParseForm()
		vid := req.FormValue("vid")
		tid := req.FormValue("tid")
		plate := req.FormValue("plate")
		frame := req.FormValue("frame")
		sType := req.FormValue("type")
		rid := req.FormValue("rid")
		enginetype := req.FormValue("enginetype")
		iType, err := strconv.Atoi(sType)
		iEngineType, _ := strconv.Atoi(enginetype)
		if err != nil || !((iType >= 1 && iType <= 6) || (iType >= 101 && iType <= 105)) {
			sErr := p.makeResultStr(1009, "参数错误", language)
			w.Write([]byte(sErr))
			return
		}

		if p.checkFields(&w, language, vid) {
			//判断是否存在设备号
			if rid != "" {
				if p.dbo.receiverType(rid) == -1 {
					sErr := p.makeResultStr(1008, "您没有该设备", language)
					w.Write([]byte(sErr))
					return
				}
			}

			vehicle := VehicleDBT{}
			vehicle.Vid = vid
			// vehicle.Cid = iCid
			vehicle.Tid = tid
			vehicle.Driver = strings.TrimSpace(req.FormValue("driver"))
			vehicle.DriverPhone = strings.TrimSpace(req.FormValue("driverphone"))
			vehicle.Plate = strings.TrimSpace(plate)
			vehicle.Frame = strings.TrimSpace(frame)
			vehicle.Type = iType
			vehicle.Rid = rid
			vehicle.EngineType = iEngineType

			err := p.dbo.vehicleEdit(&vehicle)
			var sErr string
			if err != nil {
				sErr = p.makeResultStr2(1101, "修改车辆失败", err.Error(), language)
				//sErr = p.makeResultStr(1100, err.Error(), language)
			} else {
				sErr = p.makeResultStr(0, "", language)
			}
			w.Write([]byte(sErr))
		}
	}
}
*/
//修改车辆
func (p *HttpListener) VehicleEdit2(w http.ResponseWriter, req *http.Request) {
	if language, _, ok := p.commonCheck(&w, req); ok {
		req.ParseForm()
		vid := req.FormValue("vid")
		tid := req.FormValue("tid")
		plate := req.FormValue("plate")
		frame := req.FormValue("frame")
		sType := req.FormValue("type")
		rid := req.FormValue("rid")
		dom := req.FormValue("dom")
		dop := req.FormValue("dop")
		payload := req.FormValue("payload")
		realpayload := req.FormValue("realpayload")
		drivers := req.FormValue("drivers")
		brandid := req.FormValue("brandid")
		modelid := req.FormValue("modelid")
		initmileage := req.FormValue("initmileage")
		enginetype := req.FormValue("enginetype")

		var iType, iDom, iDop, iPayload, iRealPayload, iInitMileage, iEngineType int
		var err error

		iType, err = p.checkVehicleType(sType)
		if err == nil {
			iDom, _ = strconv.Atoi(dom)
			iDop, _ = strconv.Atoi(dop)
			iPayload, _ = strconv.Atoi(payload)
			iRealPayload, _ = strconv.Atoi(realpayload)
			iInitMileage, _ = strconv.Atoi(initmileage)
			iEngineType, _ = strconv.Atoi(enginetype)
		} else {
			p.wrongParameter(&w, err, language)
			return
		}

		if err != nil || (plate == "" && frame == "") {
			p.wrongParameter(&w, nil, language)

			return
		}

		if p.checkFields(&w, language, vid) {
			//判断是否存在设备号
			if rid != "" {
				if p.dbo.receiverType(rid) == -1 {
					sErr := p.makeResultStr(1008, "您没有该设备", language)
					w.Write([]byte(sErr))
					return
				}
			}

			vehicle := VehicleInfoDBT{}
			vehicle.Vid = vid

			vehicle.Tid = tid
			if tid != "" {
				vehicle.Tids = p.dbo.getTeamParents(tid)
			}
			vehicle.Plate = strings.TrimSpace(plate)
			vehicle.Frame = strings.TrimSpace(frame)
			vehicle.Type = iType
			vehicle.Rid = rid
			vehicle.BrandID = brandid
			vehicle.ModelID = modelid
			vehicle.Dom = iDom
			vehicle.Dop = iDop
			vehicle.Payload = iPayload
			vehicle.RealPayload = iRealPayload
			vehicle.DriverIDs = strings.Split(drivers, ",")
			vehicle.InitMileage = iInitMileage
			vehicle.EngineType = iEngineType

			err := p.dbo.vehicleEdit2(&vehicle)
			var sErr string
			if err != nil {
				sErr = p.makeResultStr2(1101, "修改车辆失败", err.Error(), language)
			} else {
				sErr = p.makeResultStr(0, "", language)
			}
			w.Write([]byte(sErr))
		}
	}
}

// 删除车辆
func (p *HttpListener) VehicleRemove(w http.ResponseWriter, req *http.Request) {
	if language, _, ok := p.commonCheck(&w, req); ok {
		req.ParseForm()
		vid := req.FormValue("vid")
		if p.checkFields(&w, language, vid) {
			var sErr string

			p.dbo.vehicleRemove(vid)
			sErr = p.makeResultStr(0, "", language)
			w.Write([]byte(sErr))
		}
	}
}

// 车辆信息
func (p *HttpListener) VehicleInfo(w http.ResponseWriter, req *http.Request) {
	if language, _, ok := p.commonCheck(&w, req); ok {
		req.ParseForm()

		var sErr string

		vid := req.FormValue("vid")
		rid := req.FormValue("rid")
		if vid == "" && rid == "" {
			sErr = p.makeResultStr(1003, "缺少必要的字段", language)
			w.Write([]byte(sErr))
			return
		}

		if vid == "" {
			vid = p.dbo.getVidByRid(rid)
			if vid == "" {
				sErr = p.makeResultStr2(1024, "获取车辆信息失败", "设备未绑定车辆", language)
				w.Write([]byte(sErr))
				return
			}
		}
		vi, err := p.dbo.vehicleInfo(vid)
		if err != nil {
			sErr = p.makeResultStr2(1024, "获取车辆信息失败", err.Error(), language)
			w.Write([]byte(sErr))
		} else {
			res := make(map[string]interface{})
			res["errcode"] = 0
			res["data"] = vi
			buf, _ := json.Marshal(res)
			w.Write(buf)
		}

	}
}

// 车辆轮胎信息
func (p *HttpListener) VehicleTires(w http.ResponseWriter, req *http.Request) {
	if language, _, ok := p.commonCheck(&w, req); ok {
		req.ParseForm()

		vid := req.FormValue("vid")
		if p.checkFields(&w, language, vid) {
			vi, err := p.dbo.vehicleTires(vid)
			if err != nil {
				sErr := p.makeResultStr2(1026, "获取车辆的轮胎信息失败", err.Error(), language)
				w.Write([]byte(sErr))
			} else {
				res := make(map[string]interface{})
				res["errcode"] = 0
				res["data"] = vi
				buf, _ := json.Marshal(res)
				w.Write(buf)
			}
		}
	}
}

func (p *HttpListener) VehicleTires_v2(w http.ResponseWriter, req *http.Request) {
	if language, _, ok := p.commonCheck(&w, req); ok {
		req.ParseForm()

		vid := req.FormValue("vid")
		if p.checkFields(&w, language, vid) {
			vi, err := p.dbo.vehicleTires_v2(vid)
			if err != nil {
				sErr := p.makeResultStr2(1026, "获取车辆的轮胎信息失败", err.Error(), language)
				w.Write([]byte(sErr))
			} else {
				res := make(map[string]interface{})
				res["errcode"] = 0
				res["data"] = vi
				buf, _ := json.Marshal(res)
				w.Write(buf)
			}
		}
	}
}

// 车辆单个轮胎信息
func (p *HttpListener) VehicleTire_v2(w http.ResponseWriter, req *http.Request) {
	if language, _, ok := p.commonCheck(&w, req); ok {
		req.ParseForm()

		vid := req.FormValue("vid")
		cardid := req.FormValue("cardid")
		sn := req.FormValue("sn")

		var iCardId, iSN int
		var err error

		iCardId, err = strconv.Atoi(cardid)
		if err == nil {
			iSN, err = strconv.Atoi(sn)
		}

		if err != nil {
			sErr := p.makeResultStr(1009, "参数错误", language)
			w.Write([]byte(sErr))
			return
		}

		if p.checkFields(&w, language, vid, cardid, sn) {
			ti := p.dbo.vehicleTire(vid, iCardId, iSN)
			buf, _ := json.Marshal(ti)
			w.Write(buf)
		}
	}
}

// 账号管理----------------------------------------------------------------------------
// 账号列表
func (p *HttpListener) CustomerList(w http.ResponseWriter, req *http.Request) {
	if language, userid, ok := p.commonCheck(&w, req); ok {
		req.ParseForm()
		cid := req.FormValue("cid")
		tid := req.FormValue("tid")
		iCid, err := strconv.Atoi(cid)
		if err != nil {
			sErr := p.makeResultStr(1009, "参数错误", language)
			w.Write([]byte(sErr))
			return
		}

		if p.checkFields(&w, language, cid) {
			cl, err := p.dbo.customerList(userid, iCid, tid)
			if err != nil {
				sErr := p.makeResultStr(1100, err.Error(), language)
				w.Write([]byte(sErr))
			} else {
				res := make(map[string]interface{})
				res["errcode"] = 0
				res["customers"] = cl
				buf, _ := json.Marshal(res)
				w.Write(buf)
			}
		}
	}
}

// 添加账号
func (p *HttpListener) CustomerAdd(w http.ResponseWriter, req *http.Request) {
	if language, _, ok := p.commonCheck(&w, req); ok {
		req.ParseForm()
		cid := req.FormValue("cid")
		tid := req.FormValue("tid")
		user := req.FormValue("user")
		pass := req.FormValue("pass")
		name := req.FormValue("name")
		utype := req.FormValue("utype")
		email := req.FormValue("email")
		phone := req.FormValue("phone")
		iCid, err := strconv.Atoi(cid)
		if err != nil {
			sErr := p.makeResultStr(1009, "参数错误", language)
			w.Write([]byte(sErr))
			return
		}
		iUtype, err := p.checkCustomerType(utype)
		if err != nil {
			p.wrongParameter(&w, err, language)
			return
		}

		if p.checkFields(&w, language, cid, user, pass, name, utype) {
			customer := map[string]interface{}{"cid": iCid, "tid": tid, "user": user, "pass": pass, "uname": name,
				"utype": iUtype, "email": email, "phone": phone, "createtime": time.Now().Unix()}

			err := p.dbo.addCustomer(customer)
			if err != nil {
				sErr := p.makeResultStr2(1101, "操作失败", err.Error(), language)
				w.Write([]byte(sErr))
			} else {
				res := p.makeResultStr(0, "", language)

				w.Write([]byte(res))
			}
		}
	}
}

// 修改账号
func (p *HttpListener) CustomerEdit(w http.ResponseWriter, req *http.Request) {
	if language, _, ok := p.commonCheck(&w, req); ok {
		req.ParseForm()
		user := req.FormValue("user")
		pass := req.FormValue("pass")
		name := req.FormValue("name")
		email := req.FormValue("email")
		phone := req.FormValue("phone")
		utype := req.FormValue("utype")

		if p.checkFields(&w, language, user) {
			if pass == "" && name == "" && email == "" && phone == "" && utype == "" {
				sErr := p.makeResultStr(1009, "参数错误", language)
				w.Write([]byte(sErr))
				return
			}

			iUtype, err := p.checkCustomerType(utype)
			if err != nil {
				p.wrongParameter(&w, err, language)
				return
			}

			err = p.dbo.editCustomer(user, name, pass, phone, email, iUtype)
			if err != nil {
				sErr := p.makeResultStr2(1101, "操作失败：", err.Error(), language)
				w.Write([]byte(sErr))
			} else {
				res := p.makeResultStr(0, "", language)
				w.Write([]byte(res))
			}
		}
	}
}

// 修改账号密码
func (p *HttpListener) CustomerChangePassword(w http.ResponseWriter, req *http.Request) {
	if language, userid, ok := p.commonCheck(&w, req); ok {
		req.ParseForm()
		user := req.FormValue("user")
		pass := req.FormValue("pass")

		if p.checkFields(&w, language, user, pass) {
			err := p.dbo.customerChangePassword(userid, user, pass)
			if err != nil {
				sErr := p.makeResultStr(1011, "修改密码失败:"+err.Error(), language)
				w.Write([]byte(sErr))
			} else {
				res := p.makeResultStr(0, "", language)
				w.Write([]byte(res))
			}
		}
	}
}

// 删除账号
func (p *HttpListener) CustomerRemove(w http.ResponseWriter, req *http.Request) {
	if language, _, ok := p.commonCheck(&w, req); ok {
		req.ParseForm()
		cid := req.FormValue("cid")
		user := req.FormValue("user")

		if p.checkFields(&w, language, cid, user) {
			iCid, err := strconv.Atoi(cid)
			if err != nil {
				sErr := p.makeResultStr(1009, "参数错误", language)
				w.Write([]byte(sErr))
				return
			}
			err = p.dbo.customerRemove(iCid, user)
			if err != nil {
				res := p.makeResultStr2(1101, "操作失败", err.Error(), language)
				w.Write([]byte(res))

			} else {
				res := p.makeResultStr(0, "", language)
				w.Write([]byte(res))
			}
		}
	}
}

// 绑定微信
func (p *HttpListener) CustomerBindWechat(w http.ResponseWriter, req *http.Request) {
	if lang, userid, ok := p.commonCheck(&w, req); ok {
		req.ParseForm()

		//获取微信信息
		//微信登录的code
		code := req.FormValue("code")

		if p.checkFields(&w, lang, code) {
			client := NewWxClient(p.cfg.WeChat.AppID, p.cfg.WeChat.Secret)
			err := client.GetAccessToken(code)
			if err == nil {
				ui, err := client.GetUserInfo()
				if err == nil {
					//保存微信信息
					p.dbo.SaveCustomerWechatInfo(userid, ui.OpenID, ui.NickName, ui.HeadImgURL)
					ret := make(map[string]interface{})
					ret["errcode"] = 0
					ret["wxid"] = ui.OpenID
					ret["wxname"] = ui.NickName
					ret["wxheadimgurl"] = ui.HeadImgURL

					buf, _ := json.Marshal(ret)
					w.Write(buf)
					return
				}
			}
			if err != nil {
				sErr := p.makeResultStr2(1033, "微信绑定失败", err.Error(), lang)
				w.Write([]byte(sErr))
			}
		}
	}
	/*	if language, userid, ok := p.commonCheck(&w, req); ok {
		req.ParseForm()
		wxId := req.FormValue("wxid")
		wxName := req.FormValue("wxname")

		if p.checkFields(&w, language, wxId, wxName) {
			err := p.dbo.customerBindWechat(userid, wxId, wxName)
			if err != nil {
				res := p.makeResultStr2(1033, "微信绑定失败", err.Error(), language)
				w.Write([]byte(res))

			} else {
				res := p.makeResultStr(0, "", language)
				w.Write([]byte(res))
			}
		}
	}*/
}

// 解绑微信
func (p *HttpListener) CustomerUnbindWechat(w http.ResponseWriter, req *http.Request) {
	if language, userid, ok := p.commonCheck(&w, req); ok {
		req.ParseForm()
		code := req.FormValue("code")

		if p.checkFields(&w, language, code) {
			client := NewWxClient(p.cfg.WeChat.AppID, p.cfg.WeChat.Secret)
			err := client.GetAccessToken(code)
			if err == nil {
				err = p.dbo.customerUnbindWechat(userid, client.OpenID)
				if err == nil {
					res := p.makeResultStr(0, "", language)
					w.Write([]byte(res))
					return
				}
			}

			if err != nil {
				sErr := p.makeResultStr2(1034, "解绑微信失败", err.Error(), language)
				w.Write([]byte(sErr))
			}
		}
	}
}

func (p *HttpListener) DriverUnbindMiniProgram(w http.ResponseWriter, req *http.Request) {
	if language, _, ok := p.commonCheck(&w, req); ok {

		var param struct {
			User string `json:"user"`
		}
		buf, err := p.readBody(req)
		if err == nil {
			err = json.Unmarshal(buf, &param)
		}
		if err != nil {
			p.wrongParameter(&w, err, language)
			return
		}

		if p.checkFields(&w, language, param.User) {
			p.dbo.driverUnbindMiniProgram(param.User)
			res := p.makeResultStr(0, "", language)
			w.Write([]byte(res))
			return
		}
	}
}

// 账号登录历史
func (p *HttpListener) CustomerLoginHistory(w http.ResponseWriter, req *http.Request) {
	if language, _, ok := p.commonCheck(&w, req); ok {
		cid := req.FormValue("cid")
		user := req.FormValue("user")
		date := req.FormValue("date")
		page := req.FormValue("page")

		if p.checkFields(&w, language, cid) {
			iCid, err := strconv.Atoi(cid)
			if err != nil {
				sErr := p.makeResultStr(1009, "参数错误", language)
				w.Write([]byte(sErr))
				return
			}
			iPage, err := strconv.Atoi(page)
			if err != nil {
				iPage = 0
			}
			iDate, err := strconv.Atoi(date)
			if err != nil {
				iDate = 0
			} else if iDate < 20000000 {
				iDate += 20000000
			}

			total, res := p.dbo.customerLoginHistory(iCid, user, iDate, iPage)
			ret := make(map[string]interface{})
			ret["errcode"] = 0
			ret["total"] = total
			ret["datas"] = res

			buf, _ := json.Marshal(ret)
			w.Write(buf)
		}
	}
}

// 报警管理----------------------------------------------------------------------------
// 报警列表
func (p *HttpListener) TireWarningList(w http.ResponseWriter, req *http.Request) {
	if _, userid, ok := p.commonCheck(&w, req); ok {
		req.ParseForm()
		rid := req.FormValue("rid")
		date := req.FormValue("date")
		stype := req.FormValue("type")
		cardid := req.FormValue("cardid")
		sn := req.FormValue("sn")
		status := req.FormValue("status")
		page := req.FormValue("page")

		iPage, err := strconv.Atoi(page)
		if err != nil {
			iPage = 0
		}
		iStatus, err := strconv.Atoi(status)
		if err != nil {
			iStatus = 0
		}
		iCardId, err := strconv.Atoi(cardid)
		if err != nil {
			iCardId = -1
		}
		iSN, err := strconv.Atoi(sn)
		if err != nil {
			iSN = -1
		}

		total, res := p.dbo.tireWarningList(userid, rid, date, stype, iCardId, iSN, iStatus, iPage)

		ret := make(map[string]interface{})
		ret["errcode"] = 0
		ret["total"] = total
		ret["warnings"] = res

		buf, _ := json.Marshal(ret)
		w.Write(buf)
	}
}

// 报警列表v2
func (p *HttpListener) TireWarningListV2(w http.ResponseWriter, req *http.Request) {
	if language, userid, ok := p.commonCheck(&w, req); ok {
		req.ParseForm()
		cids := req.FormValue("cids")
		tids := req.FormValue("tids")
		rid := req.FormValue("rid")
		plate := req.FormValue("plate")
		date := req.FormValue("date")
		stype := req.FormValue("type")
		cardid := req.FormValue("cardid")
		sn := req.FormValue("sn")
		status := req.FormValue("status")
		page := req.FormValue("page")

		iPage, err := strconv.Atoi(page)
		if err != nil {
			iPage = 0
		}
		iStatus, err := strconv.Atoi(status)
		if err != nil {
			iStatus = 0
		}
		iCardId, err := strconv.Atoi(cardid)
		if err != nil {
			iCardId = -1
		}
		iSN, err := strconv.Atoi(sn)
		if err != nil {
			iSN = -1
		}

		var arrCids, arrTids []string
		if cids != "" {
			arrCids = strings.Split(cids, ",")
		}
		if tids != "" {
			arrTids = strings.Split(tids, ",")
		}

		iUserType := p.dbo.userType(userid)
		//不是系统管理员，不允许查询所有数据，cid不允许为0
		if iUserType != UserTypeSystemUser {
			s := p.makeResultStr(1006, "非法访问", language)
			b := false

			if len(arrCids) == 0 && len(arrTids) == 0 {
				b = true
			} else {
				for _, v := range arrCids {
					if v == "0" {
						b = true
						break
					}
				}
			}

			if b {
				w.Write([]byte(s))
				return
			}
		}

		iCids := make([]int, 0)
		iTempCid := 0
		for _, v := range arrCids {
			if v != "" {
				iTempCid, err = strconv.Atoi(v)
				if err == nil {
					iCids = append(iCids, iTempCid)
				}
			}
		}

		if rid == "" && plate != "" {
			rid = p.dbo.getRidByPlate(plate)
		}

		total, res := p.dbo.tireWarningListV2(iCids, arrTids, rid, date, stype, iCardId, iSN, iStatus, iPage)

		ret := make(map[string]interface{})
		ret["errcode"] = 0
		ret["total"] = total
		ret["warnings"] = res

		buf, _ := json.Marshal(ret)
		w.Write(buf)
	}
}

func (p *HttpListener) TireWarningListV3(w http.ResponseWriter, req *http.Request) {
	if language, userid, ok := p.commonCheck(&w, req); ok {
		req.ParseForm()
		cids := req.FormValue("cids")
		tids := req.FormValue("tids")
		rid := req.FormValue("rid")
		plate := req.FormValue("plate")
		date := req.FormValue("date")
		stype := req.FormValue("type")
		cardid := req.FormValue("cardid")
		sn := req.FormValue("sn")
		status := req.FormValue("status")
		page := req.FormValue("page")
		count := req.FormValue("count")

		iPage, err := strconv.Atoi(page)
		if err != nil {
			iPage = 0
		}
		iCount, err := strconv.Atoi(count)
		if err != nil || iCount > 50 {
			iCount = 50
		}
		iStatus, err := strconv.Atoi(status)
		if err != nil {
			iStatus = 0
		}
		iCardId, err := strconv.Atoi(cardid)
		if err != nil {
			iCardId = -1
		}
		iSN, err := strconv.Atoi(sn)
		if err != nil {
			iSN = -1
		}

		var arrCids, arrTids []string
		if cids != "" {
			arrCids = strings.Split(cids, ",")
		}
		if tids != "" {
			arrTids = strings.Split(tids, ",")
		}

		iUserType := p.dbo.userType(userid)

		if iUserType != UserTypeSystemUser {
			s := p.makeResultStr(1006, "非法访问", language)
			b := false

			if len(arrCids) == 0 && len(arrTids) == 0 {
				b = true
			} else {
				for _, v := range arrCids {
					if v == "0" {
						b = true
						break
					}
				}
			}

			if b {
				w.Write([]byte(s))
				return
			}
		}

		iCids := make([]int, 0)
		iTempCid := 0
		for _, v := range arrCids {
			if v != "" {
				iTempCid, err = strconv.Atoi(v)
				if err == nil {
					iCids = append(iCids, iTempCid)
				}
			}
		}

		if rid == "" && plate != "" {
			rid = p.dbo.getRidByPlate(plate)
		}

		total, res := p.dbo.tireWarningListV3(iCids, arrTids, rid, date, stype, iCardId, iSN, iStatus, iPage, iCount)

		ret := make(map[string]interface{})
		ret["errcode"] = 0
		ret["total"] = total
		ret["warnings"] = res

		buf, _ := json.Marshal(ret)
		w.Write(buf)
	}
}

// 报警详情
func (p *HttpListener) TireWarningDetail(w http.ResponseWriter, req *http.Request) {
	if language, _, ok := p.commonCheck(&w, req); ok {
		id := req.FormValue("id")
		if p.checkFields(&w, language, id) {
			gpsType := req.FormValue("gpstype")
			if gpsType == "" {
				gpsType = GpsBd09
			}
			res, err := p.dbo.tireWarningDetail(id, gpsType)
			if err != nil {
				sErr := p.makeResultStr(2000, "数据库查询失败"+err.Error(), language)
				w.Write([]byte(sErr))
				return
			}
			ret := make(map[string]interface{})
			ret["errcode"] = 0
			ret["detail"] = res

			buf, _ := json.Marshal(ret)
			w.Write(buf)
		}
	}
}

// 报警处理
func (p *HttpListener) TireWarningHandle(w http.ResponseWriter, req *http.Request) {
	if language, _, ok := p.commonCheck(&w, req); ok {
		id := req.FormValue("id")
		misalert := req.FormValue("misalert")
		result := req.FormValue("result")

		if p.checkFields(&w, language, id) {
			iMisAlert, err := strconv.Atoi(misalert)
			if err != nil {
				//默认不是误报
				iMisAlert = 0
			}
			p.dbo.tireWarningHandle(id, iMisAlert, result)

			sErr := p.makeResultStr(0, "", language)
			w.Write([]byte(sErr))
		}
	}
}

// 拨打报警电话
func (p *HttpListener) TireWarningMakeCall(w http.ResponseWriter, req *http.Request) {
	if language, _, ok := p.commonCheck(&w, req); ok {
		id := req.FormValue("id")
		phone := req.FormValue("phone")
		text := req.FormValue("text")

		if p.checkFields(&w, language, id, phone, text) {
			err := p.makeCall(phone, text)
			var res string
			if err != nil {
				res = p.makeResultStr2(1029, "拨打电话失败", err.Error(), language)
			} else {
				res = p.makeResultStr(0, "", language)
			}
			w.Write([]byte(res))
		}
	}
}

// 是否有新报警
func (p *HttpListener) TireWarningNew(w http.ResponseWriter, req *http.Request) {
	if language, _, ok := p.commonCheck(&w, req); ok {
		cids := req.FormValue("cids")
		tids := req.FormValue("tids")
		timeStamp := req.FormValue("t") //时间戳

		if p.checkFields(&w, language, timeStamp) {
			iTs, err := strconv.Atoi(timeStamp)
			if err != nil || (cids == "" && tids == "") { //cids和tids不能同时为空
				sErr := p.makeResultStr(1009, "参数错误", language)
				w.Write([]byte(sErr))
				return
			}
			iT := TimeStampToInt(iTs)

			var iCidArray []int
			var tidArray []string

			cids = strings.TrimSpace(cids)
			if cids != "" {
				if cids[len(cids)-1] == ',' {
					cids = tids[:len(cids)-1]
				}
				cidArray := strings.Split(cids, ",")
				iCidArray = make([]int, 0)
				iTemp := 0
				for _, v := range cidArray {
					iTemp, err = strconv.Atoi(v)
					if err == nil {
						iCidArray = append(iCidArray, iTemp)
					}
				}
			}

			tids = strings.TrimSpace(tids)
			if tids != "" {
				if tids[len(tids)-1] == ',' {
					tids = tids[:len(tids)-1]
				}
				tidArray = strings.Split(tids, ",")
			}
			count := p.dbo.tirewarningNew(iCidArray, tidArray, iT)

			res := fmt.Sprintf(`{"errcode":0,"count":%d}`, count)
			w.Write([]byte(res))
		}
	}
}

// 设置关注的车队
func (p *HttpListener) TireWarningSetConcernedTeams(w http.ResponseWriter, req *http.Request) {
	if _, userid, ok := p.commonCheck(&w, req); ok {
		cids := req.FormValue("cids")
		tids := req.FormValue("tids")

		var iCidArray []int
		var tidArray []string

		cids = strings.TrimSpace(cids)
		if cids != "" {
			if cids[len(cids)-1] == ',' {
				cids = tids[:len(cids)-1]
			}
			cidArray := strings.Split(cids, ",")
			iCidArray = make([]int, 0)
			iTemp := 0
			var err error
			for _, v := range cidArray {
				iTemp, err = strconv.Atoi(v)
				if err == nil {
					iCidArray = append(iCidArray, iTemp)
				}
			}
		}

		tids = strings.TrimSpace(tids)
		if tids != "" {
			if tids[len(tids)-1] == ',' {
				tids = tids[:len(tids)-1]
			}
			tidArray = strings.Split(tids, ",")
		}
		p.dbo.tirewarningSetConcernedTeams(userid, iCidArray, tidArray)

		res := p.makeResultStr(0, "", "")
		w.Write([]byte(res))
	}
}

// 已关注的车队
func (p *HttpListener) TireWarningConcernedTeams(w http.ResponseWriter, req *http.Request) {
	if language, userid, ok := p.commonCheck(&w, req); ok {
		cts, err := p.dbo.tirewarningConcernedTeams(userid)

		if err != nil {
			sErr := p.makeResultStr(2001, err.Error(), language)
			w.Write([]byte(sErr))
			return
		}

		ret := make(map[string]interface{})
		ret["errcode"] = 0
		ret["companies"] = cts.Companies
		ret["teams"] = cts.Teams

		buf, _ := json.Marshal(ret)
		w.Write(buf)
	}
}

// 设置关注的报警类别
func (p *HttpListener) TireWarningSetConcernedTypes(w http.ResponseWriter, req *http.Request) {
	if _, userid, ok := p.commonCheck(&w, req); ok {
		types := req.FormValue("types")

		aTypes := strings.Split(types, ",")
		aiTypes := make([]int, 0)
		var iType int
		var err error

		for _, v := range aTypes {
			iType, err = strconv.Atoi(v)
			if err == nil {
				aiTypes = append(aiTypes, iType)
			}
		}

		p.dbo.tirewarningSetConcernedTypes(userid, aiTypes)

		res := p.makeResultStr(0, "", "")
		w.Write([]byte(res))
	}
}

// 已关注的报警类别
func (p *HttpListener) TireWarningConcernedTypes(w http.ResponseWriter, req *http.Request) {
	if _, userid, ok := p.commonCheck(&w, req); ok {
		cts := p.dbo.tirewarningConcernedTypes(userid)

		ret := make(map[string]interface{})
		ret["errcode"] = 0
		ret["types"] = cts

		buf, _ := json.Marshal(ret)
		w.Write(buf)
	}
}

// 设置报警的邮箱信息
func (p *HttpListener) TireWarningSetMail(w http.ResponseWriter, req *http.Request) {
	if language, userid, ok := p.commonCheck(&w, req); ok {
		req.ParseForm()
		send := req.FormValue("send")
		smtp := req.FormValue("smtp")
		port := req.FormValue("port")
		user := req.FormValue("user")
		pass := req.FormValue("pass")
		to := req.FormValue("to")

		bSend, err := strconv.ParseBool(send)
		if err != nil {
			bSend = false
		}

		if bSend && !p.checkFields(&w, language, smtp, port, user, pass, to) {
			//如果要发送邮件，则邮箱信息不能为空
			return
		}

		am := AlertMailT{Send: bSend, SMTP: smtp, Port: port, User: user, Pass: pass, To: to}
		p.dbo.tirewarningSetMail(userid, &am)

		res := p.makeResultStr(0, "", language)
		w.Write([]byte(res))
	}
}

// 已设置的报警的邮箱信息
func (p *HttpListener) TireWarningMail(w http.ResponseWriter, req *http.Request) {
	if _, userid, ok := p.commonCheck(&w, req); ok {
		am := p.dbo.tirewarningMail(userid)

		ret := make(map[string]interface{})
		ret["errcode"] = 0
		ret["mail"] = am

		buf, _ := json.Marshal(ret)
		w.Write(buf)
	}
}

// 轮胎管理----------------------------------------------------------------------------
// 轮胎品牌列表
func (p *HttpListener) TireBrandList(w http.ResponseWriter, req *http.Request) {
	if language, userid, ok := p.commonCheck(&w, req); ok {
		req.ParseForm()
		cid := req.FormValue("cid")
		page := req.FormValue("page")

		if p.checkFields(&w, language, cid) {
			var iCid, iPage int
			var err error

			iCid, err = strconv.Atoi(cid)
			if err != nil {
				sErr := p.makeResultStr(1009, "参数错误", language)
				w.Write([]byte(sErr))
				return
			}
			if page == "" {
				iPage = -1
			} else {
				iPage, err = strconv.Atoi(page)
				if err != nil {
					iPage = 0
				}
			}

			total, res := p.dbo.tireBrandList(userid, iCid, iPage)

			ret := make(map[string]interface{})
			ret["errcode"] = 0
			ret["total"] = total
			ret["tirebrands"] = res

			buf, _ := json.Marshal(ret)
			w.Write(buf)
		}
	}
}

// 添加轮胎品牌
func (p *HttpListener) TireBrandAdd(w http.ResponseWriter, req *http.Request) {
	if language, _, ok := p.commonCheck(&w, req); ok {
		req.ParseForm()
		cid := req.FormValue("cid")
		name := req.FormValue("name")
		if p.checkFields(&w, language, cid, name) {
			iCid, err := strconv.Atoi(cid)
			var sErr string
			var buf []byte
			if err != nil {
				sErr = p.makeResultStr(1009, "参数错误", language)
				w.Write([]byte(sErr))
				return
			}

			brandid, err := p.dbo.tireBrandAdd(iCid, name)

			if err != nil {
				sErr = p.makeResultStr(1101, err.Error(), language)
				buf = []byte(sErr)
			} else {
				ret := make(map[string]interface{})
				ret["errcode"] = 0
				ret["brandid"] = brandid
				buf, _ = json.Marshal(ret)
			}

			w.Write(buf)
		}
	}
}

// 修改轮胎品牌名称
func (p *HttpListener) TireBrandEdit(w http.ResponseWriter, req *http.Request) {
	if language, _, ok := p.commonCheck(&w, req); ok {
		req.ParseForm()
		cid := req.FormValue("cid")
		brandId := req.FormValue("brandid")
		name := req.FormValue("name")
		if p.checkFields(&w, language, cid, name) {
			var sErr string
			var buf []byte
			var err error
			var iCid, iBrandId int

			iCid, err = strconv.Atoi(cid)
			if err == nil {
				iBrandId, err = strconv.Atoi(brandId)
			}
			if err != nil {
				sErr = p.makeResultStr(1009, "参数错误", language)
				w.Write([]byte(sErr))
				return
			}

			err = p.dbo.tireBrandEdit(iCid, iBrandId, name)

			if err != nil {
				sErr = p.makeResultStr(1101, err.Error(), language)
			} else {
				sErr = p.makeResultStr(0, "", language)
			}
			buf = []byte(sErr)

			w.Write(buf)
		}
	}
}

// 删除轮胎品牌
func (p *HttpListener) TireBrandRemove(w http.ResponseWriter, req *http.Request) {
	if language, _, ok := p.commonCheck(&w, req); ok {
		req.ParseForm()
		cid := req.FormValue("cid")
		brandId := req.FormValue("brandid")
		if p.checkFields(&w, language, cid) {
			var sErr string
			var buf []byte
			var err error
			var iCid, iBrandId int

			iCid, err = strconv.Atoi(cid)
			if err == nil {
				iBrandId, err = strconv.Atoi(brandId)
			}
			if err != nil {
				sErr = p.makeResultStr(1009, "参数错误", language)
				w.Write([]byte(sErr))
				return
			}

			p.dbo.tireBrandRemove(iCid, iBrandId)

			sErr = p.makeResultStr(0, "", language)
			buf = []byte(sErr)

			w.Write(buf)
		}
	}
}

// 轮胎规格列表
func (p *HttpListener) TireModelList(w http.ResponseWriter, req *http.Request) {
	if language, _, ok := p.commonCheck(&w, req); ok {
		bid := req.FormValue("brandid")
		page := req.FormValue("page")

		if p.checkFields(&w, language, bid) {
			var iBid, iPage int
			var err error

			iBid, err = strconv.Atoi(bid)
			if err == nil {
				if page == "" {
					iPage = -1
				} else {
					iPage, err = strconv.Atoi(page)
				}
			}
			if err != nil {
				sErr := p.makeResultStr(1009, "参数错误", language)
				w.Write([]byte(sErr))
				return
			}
			total, res := p.dbo.tireModelList(iBid, iPage)

			ret := make(map[string]interface{})
			ret["errcode"] = 0
			ret["total"] = total
			ret["tiremodels"] = res

			buf, _ := json.Marshal(ret)
			w.Write(buf)
		}
	}
}

// 轮胎规格详情
func (p *HttpListener) TireModelInfo(w http.ResponseWriter, req *http.Request) {
	if language, _, ok := p.commonCheck(&w, req); ok {
		bid := req.FormValue("brandid")
		model := req.FormValue("model")
		pattern := req.FormValue("pattern")

		if p.checkFields(&w, language, bid, model) {
			var iBid int
			var err error

			iBid, err = strconv.Atoi(bid)
			if err != nil {
				sErr := p.makeResultStr(1009, "参数错误", language)
				w.Write([]byte(sErr))
				return
			}
			res := p.dbo.tireModelInfo(iBid, model, pattern)

			ret := make(map[string]interface{})
			ret["errcode"] = 0
			ret["model"] = res

			buf, _ := json.Marshal(ret)
			w.Write(buf)
		}
	}
}

// 轮胎规格数组
func (p *HttpListener) TireModels(w http.ResponseWriter, req *http.Request) {
	if language, _, ok := p.commonCheck(&w, req); ok {
		bid := req.FormValue("brandid")

		if p.checkFields(&w, language, bid) {
			var iBid int
			var err error

			iBid, err = strconv.Atoi(bid)
			if err != nil {
				sErr := p.makeResultStr(1009, "参数错误", language)
				w.Write([]byte(sErr))
				return
			}
			res := p.dbo.tireModels(iBid)

			ret := make(map[string]interface{})
			ret["errcode"] = 0
			ret["tiremodels"] = res

			buf, _ := json.Marshal(ret)
			w.Write(buf)
		}
	}
}

// 轮胎花纹数组
func (p *HttpListener) TirePatterns(w http.ResponseWriter, req *http.Request) {
	if language, _, ok := p.commonCheck(&w, req); ok {
		bid := req.FormValue("brandid")
		mid := req.FormValue("model")

		if p.checkFields(&w, language, bid, mid) {
			var iBid int
			var err error

			iBid, err = strconv.Atoi(bid)
			if err != nil {
				sErr := p.makeResultStr(1009, "参数错误", language)
				w.Write([]byte(sErr))
				return
			}
			res := p.dbo.tirePatterns(iBid, mid)

			ret := make(map[string]interface{})
			ret["errcode"] = 0
			ret["tirepatterns"] = res

			buf, _ := json.Marshal(ret)
			w.Write(buf)
		}
	}
}

// 添加轮胎规格
func (p *HttpListener) TireModelAdd(w http.ResponseWriter, req *http.Request) {
	if language, _, ok := p.commonCheck(&w, req); ok {
		req.ParseForm()
		cid := req.FormValue("cid")
		brandid := req.FormValue("brandid")
		model := req.FormValue("model")
		name := req.FormValue("name")
		pattern := req.FormValue("pattern")
		depth := req.FormValue("depth")
		mileage := req.FormValue("mileage")
		pressure := req.FormValue("pressure")
		load := req.FormValue("load")
		if p.checkFields(&w, language, cid, brandid, model, name, pattern, depth) {
			var err error
			var sErr string
			var iCid, iBrandId, iMileage, iLoad int
			var iPressure float64
			var fDepth float64

			iCid, err = strconv.Atoi(cid)
			if err == nil {
				iBrandId, err = strconv.Atoi(brandid)
				if err == nil {
					fDepth, err = strconv.ParseFloat(depth, 32)
					if err == nil {
						iMileage, err = strconv.Atoi(mileage)
						if err != nil {
							iMileage = 0
						}
						iPressure, err = strconv.ParseFloat(pressure, 32)
						if err != nil {
							iPressure = 0
						}
						iLoad, err = strconv.Atoi(load)
						if err != nil {
							iLoad = 0
						}
						err = nil
					}
				}
			}
			if err != nil {
				sErr = p.makeResultStr(1009, "参数错误", language)
				w.Write([]byte(sErr))
				return
			}

			err = p.dbo.tireModelAdd(iCid, iBrandId, model, name, pattern, fDepth, iMileage, iPressure, iLoad)

			if err != nil {
				sErr = p.makeResultStr2(1101, "操作失败", err.Error(), language)
			} else {
				sErr = p.makeResultStr(0, "", language)
			}

			w.Write([]byte(sErr))
		}
	}
}

// 修改轮胎规格
func (p *HttpListener) TireModelEdit(w http.ResponseWriter, req *http.Request) {
	if language, _, ok := p.commonCheck(&w, req); ok {
		req.ParseForm()
		cid := req.FormValue("cid")
		brandid := req.FormValue("brandid")
		model := req.FormValue("model")
		name := req.FormValue("name")
		pattern := req.FormValue("pattern")
		depth := req.FormValue("depth")
		mileage := req.FormValue("mileage")
		pressure := req.FormValue("pressure")
		load := req.FormValue("load")
		if p.checkFields(&w, language, cid, brandid, model, name, pattern, depth) {
			var err error
			var sErr string
			var iCid, iBrandId, iMileage, iLoad int
			var iPressure, fDepth float64

			iCid, err = strconv.Atoi(cid)
			if err == nil {
				iBrandId, err = strconv.Atoi(brandid)
				if err == nil {
					fDepth, err = strconv.ParseFloat(depth, 32)
					if err == nil {
						iMileage, err = strconv.Atoi(mileage)
						if err != nil {
							iMileage = 0
						}
						iPressure, err = strconv.ParseFloat(pressure, 32)
						if err != nil {
							iPressure = 0
						}
						iLoad, err = strconv.Atoi(load)
						if err != nil {
							iLoad = 0
						}
						err = nil
					}
				}
			}
			if err != nil {
				sErr = p.makeResultStr(1009, "参数错误", language)
				w.Write([]byte(sErr))
				return
			}

			err = p.dbo.tireModelEdit(iCid, iBrandId, model, name, pattern, fDepth, iMileage, iPressure, iLoad)

			if err != nil {
				sErr = p.makeResultStr(1101, err.Error(), language)
			} else {
				sErr = p.makeResultStr(0, "", language)
			}

			w.Write([]byte(sErr))
		}
	}
}

// 删除轮胎规格
func (p *HttpListener) TireModelRemove(w http.ResponseWriter, req *http.Request) {
	if language, _, ok := p.commonCheck(&w, req); ok {
		req.ParseForm()
		cid := req.FormValue("cid")
		brandId := req.FormValue("brandid")
		model := req.FormValue("model")
		if p.checkFields(&w, language, cid, brandId, model) {
			var sErr string
			var buf []byte
			var err error
			var iCid, iBrandId int

			iCid, err = strconv.Atoi(cid)
			if err == nil {
				iBrandId, err = strconv.Atoi(brandId)
			}
			if err != nil {
				sErr = p.makeResultStr(1009, "参数错误", language)
				w.Write([]byte(sErr))
				return
			}

			p.dbo.tireModelRemove(iCid, iBrandId, model)

			sErr = p.makeResultStr(0, "", language)
			buf = []byte(sErr)

			w.Write(buf)
		}
	}
}

// 设备轮胎信息
func (p *HttpListener) TireSet(w http.ResponseWriter, req *http.Request) {
	if language, _, ok := p.commonCheck(&w, req); ok {
		cid := req.FormValue("cid")
		tid := req.FormValue("tid")
		rid := req.FormValue("rid")
		vid := req.FormValue("vid")
		cardid := req.FormValue("cardid")
		sn := req.FormValue("sn")
		brandid := req.FormValue("brandid")
		model := req.FormValue("model")
		pattern := req.FormValue("pattern")
		tno := req.FormValue("tno")
		oldTno := req.FormValue("oldtno")
		sid := req.FormValue("sid")
		oldsid := req.FormValue("oldsid")
		dot := req.FormValue("dot")
		mileage := req.FormValue("mileage")
		depths := req.FormValue("depths")
		operator := req.FormValue("operator")
		operateTime := req.FormValue("operatetime")
		status := req.FormValue("status")

		if p.checkFields(&w, language, cid, cardid, sn, brandid, model, tno) {
			var err error
			var iCid, iCardID, iSN, iMileage, iOperateTime, iBrandId, iStatus int
			var fMileage float64

			iCid, err = strconv.Atoi(cid)
			if err == nil {
				iBrandId, err = strconv.Atoi(brandid)
				if err == nil {
					iCardID, err = strconv.Atoi(cardid)
					if err == nil {
						iSN, err = strconv.Atoi(sn)
						if err == nil {
							fMileage, _ = strconv.ParseFloat(mileage, 64)

							iMileage = int(fMileage)

							iOperateTime, _ = strconv.Atoi(operateTime)
						}
					}
				}
			}
			if err == nil {
				if rid == "" && vid == "" {
					err = errors.New("设备号与车辆ID不能同时为空。")
				}
			}
			if err != nil {
				sErr := p.makeResultStr2(1009, "参数错误", err.Error(), language)
				w.Write([]byte(sErr))
				return
			}

			iStatus, err = strconv.Atoi(status)
			if err != nil {
				iStatus = -1
			}

			err = p.dbo.tireSet(iCid, tid, rid, vid, iCardID, iSN, iBrandId, model, pattern, tno,
				oldTno, dot, iMileage, depths, operator, iOperateTime, iStatus)

			//如果新老SID不同，则下发对码
			if err == nil && sid != oldsid {
				tempRecode := make(map[string]interface{})
				tempRecode["rid"] = rid
				tempRecode["type"] = p.dbo.receiverType(rid)

				tempSensors := make([]interface{}, 0)
				tempSensor := bson.M{"sid": sid, "cardid": iCardID, "sn": iSN}
				tempSensors = append(tempSensors, tempSensor)

				tempRecode["sensors"] = tempSensors

				buf, _ := json.Marshal(tempRecode)
				_, err = p.Post(p.cfg.ReceiverdURL+"/receiver/bindsensor", "", buf)
			}

			ret := make(map[string]interface{})
			if err == nil {
				ret["errcode"] = 0
			} else {
				ret["errcode"] = 2000
				ret["msg"] = "绑定失败：" + err.Error()
			}

			buf, _ := json.Marshal(ret)
			w.Write(buf)
		}
	}
}

// 轮胎列表
func (p *HttpListener) TireList(w http.ResponseWriter, req *http.Request) {
	if language, userid, ok := p.commonCheck(&w, req); ok {
		cid := req.FormValue("cid")
		tid := req.FormValue("tid")
		tno := req.FormValue("tno")
		page := req.FormValue("page")

		if p.checkFields(&w, language, cid) {
			iCid, err := strconv.Atoi(cid)
			if err != nil {
				sErr := p.makeResultStr(1009, "参数错误", language)
				w.Write([]byte(sErr))
				return
			}
			iPage, err := strconv.Atoi(page)
			if err != nil {
				iPage = 0
			}

			total, res := p.dbo.tireList(userid, iCid, tid, tno, iPage)
			ret := make(map[string]interface{})
			ret["errcode"] = 0
			ret["total"] = total
			ret["datas"] = res

			buf, _ := json.Marshal(ret)
			w.Write(buf)
		}
	}
}

// 轮胎查询
func (p *HttpListener) TireQuery(w http.ResponseWriter, req *http.Request) {
	if language, _, ok := p.commonCheck(&w, req); ok {
		cid := req.FormValue("cid")
		tid := req.FormValue("tid")
		wid := req.FormValue("wid")
		bid := req.FormValue("bid")
		mid := req.FormValue("mid")
		tno := req.FormValue("tno")
		sensor := req.FormValue("sensor")
		dot := req.FormValue("dot")
		rfid := req.FormValue("rfid")
		status := req.FormValue("status")
		instock := req.FormValue("instock")
		threshold1 := req.FormValue("threshold1")
		threshold2 := req.FormValue("threshold2")
		page := req.FormValue("page")

		if p.checkFields(&w, language, cid) {
			var err error
			var iCid, iWid, iBid, iStatus, iPage, iThreshold1, iThreshold2, iInStock int

			iCid, err = strconv.Atoi(cid)

			if err != nil {
				p.wrongParameter(&w, err, language)
				return
			}

			iWid, err = strconv.Atoi(wid)
			if err != nil {
				iWid = 0
			}

			iBid, err = strconv.Atoi(bid)
			if err != nil {
				iBid = 0
			}

			iStatus, err = strconv.Atoi(status)
			if err != nil {
				iStatus = -1
			}

			iInStock, err = strconv.Atoi(instock)
			if err != nil || iInStock < 0 || iInStock > 1 {
				iInStock = -1
			}

			iThreshold1, err = strconv.Atoi(threshold1)
			if err != nil {
				iThreshold1 = 0
			}

			iThreshold2, err = strconv.Atoi(threshold2)
			if err != nil {
				iThreshold2 = 0
			}

			iPage, err = strconv.Atoi(page)
			if err != nil {
				iPage = 0
			}

			total, res := p.dbo.tireQuery(iCid, tid, iWid, iBid, mid, tno, sensor, dot, rfid, iStatus, iInStock,
				iThreshold1, iThreshold2, iPage)
			ret := make(map[string]interface{})
			ret["errcode"] = 0
			ret["total"] = total
			ret["tires"] = res

			buf, _ := json.Marshal(ret)
			w.Write(buf)
		}
	}
}

// 根据RFID查询轮胎号
func (p *HttpListener) TireByRFID(w http.ResponseWriter, req *http.Request) {
	if language, _, ok := p.commonCheck(&w, req); ok {
		cid := req.FormValue("cid")
		rfid := req.FormValue("rfid")

		if p.checkFields(&w, language, cid, rfid) {
			var err error
			var iCid int
			iCid, err = strconv.Atoi(cid)

			if err != nil {
				p.wrongParameter(&w, err, language)
				return
			}

			tno := p.dbo.tireByRFID(iCid, rfid)
			buf := p.makeResultBuffer("tno", tno)
			w.Write(buf)

		}
	}
}

// 添加轮胎
func (p *HttpListener) TireAdd(w http.ResponseWriter, req *http.Request) {
	if lang, userid, ok := p.commonCheck(&w, req); ok {
		cid := req.FormValue("cid")
		tid := req.FormValue("tid")
		wid := req.FormValue("wid")
		bid := req.FormValue("bid")
		mid := req.FormValue("model")
		pattern := req.FormValue("pattern")
		tno := req.FormValue("tno")
		dot := req.FormValue("dot")
		rfid := req.FormValue("rfid")
		depths := req.FormValue("depths")
		status := req.FormValue("status")
		intodate := req.FormValue("intodate")
		reason := req.FormValue("reason")

		if p.checkFields(&w, lang, cid, bid, mid, tno, intodate) {
			var err error
			var iCid, iWid, iBid, iStatus, iIntodate int
			iCid, err = strconv.Atoi(cid)

			if err == nil {
				iBid, err = strconv.Atoi(bid)
				if err == nil {
					iIntodate, err = strconv.Atoi(intodate)
				}
			}

			if err != nil {
				p.wrongParameter(&w, err, lang)
				return
			}

			iWid, err = strconv.Atoi(wid)
			if err != nil {
				iWid = 0
			}

			iStatus, err = strconv.Atoi(status)
			if err != nil {
				iStatus = -1
			}

			var sErr string
			err = p.dbo.tireAdd(userid, iCid, tid, iWid, iBid, mid, pattern, tno, dot, rfid, depths, iStatus, iIntodate, reason)
			if err == nil {
				sErr = p.makeResultStr(0, "", "")
			} else {
				sErr = p.makeResultStr2(1101, "操作失败", err.Error(), lang)
			}

			w.Write([]byte(sErr))
		}
	}
}

// 修改轮胎信息
func (p *HttpListener) TireEdit(w http.ResponseWriter, req *http.Request) {
	if lang, userid, ok := p.commonCheck(&w, req); ok {
		cid := req.FormValue("cid")
		tid := req.FormValue("tid")
		wid := req.FormValue("wid")
		bid := req.FormValue("bid")
		mid := req.FormValue("model")
		pattern := req.FormValue("pattern")
		tno := req.FormValue("tno")
		dot := req.FormValue("dot")
		rfid := req.FormValue("rfid")
		depths := req.FormValue("depths")
		status := req.FormValue("status")
		intodate := req.FormValue("intodate")
		reason := req.FormValue("reason")

		if p.checkFields(&w, lang, cid, tno) {
			var err error
			var iCid, iWid, iBid, iStatus, iIntodate int
			iCid, err = strconv.Atoi(cid)

			if err == nil {
				iBid, err = strconv.Atoi(bid)
				if err == nil {
					iIntodate, err = strconv.Atoi(intodate)
				}
			}

			if err != nil {
				p.wrongParameter(&w, err, lang)
				return
			}

			iWid, err = strconv.Atoi(wid)
			if err != nil {
				iWid = 0
			}

			iStatus, err = strconv.Atoi(status)
			if err != nil {
				iStatus = -1
			}

			var sErr string
			err = p.dbo.tireEdit(userid, iCid, tid, iWid, iBid, mid, pattern, tno, dot, rfid, depths, iStatus, iIntodate, reason)
			if err == nil {
				sErr = p.makeResultStr(0, "", "")
			} else {
				sErr = p.makeResultStr2(1101, "操作失败", err.Error(), lang)
			}

			w.Write([]byte(sErr))
		}
	}
}

// 删除轮胎
func (p *HttpListener) TireDelete(w http.ResponseWriter, req *http.Request) {
	if lang, userid, ok := p.commonCheck(&w, req); ok {
		cid := req.FormValue("cid")
		tno := req.FormValue("tno")

		var sErr string

		uType := p.dbo.userType(userid)
		if uType != UserTypeSystemUser && uType != UserTypeAdministrator {
			sErr = p.makeResultStr(1014, "无此权限", lang)
			w.Write([]byte(sErr))
			return
		}

		if p.checkFields(&w, lang, cid, tno) {
			var err error
			var iCid int
			iCid, _ = strconv.Atoi(cid)

			err = p.dbo.tireDelete(iCid, tno)
			if err == nil {
				sErr = p.makeResultStr(0, "", "")
			} else {
				sErr = p.makeResultStr2(1101, "操作失败", "无此轮胎号", lang)
			}

			w.Write([]byte(sErr))
		}
	}
}

// 轮胎基本信息
func (p *HttpListener) TireBaseInfo(w http.ResponseWriter, req *http.Request) {
	if lang, _, ok := p.commonCheck(&w, req); ok {
		cid := req.FormValue("cid")
		tno := req.FormValue("tno")

		if p.checkFields(&w, lang, cid, tno) {
			var err error
			var iCid int
			iCid, err = strconv.Atoi(cid)

			if err != nil {
				p.wrongParameter(&w, err, lang)
				return
			}

			res := p.dbo.tireBaseInfo(iCid, tno)
			buf := p.makeResultBuffer("data", res)
			w.Write(buf)
		}
	}
}

// 轮胎生命周期
func (p *HttpListener) TireLifeCircle(w http.ResponseWriter, req *http.Request) {
	if lang, _, ok := p.commonCheck(&w, req); ok {
		cid := req.FormValue("cid")
		tno := req.FormValue("tno")

		if p.checkFields(&w, lang, cid, tno) {
			var err error
			var iCid int
			iCid, err = strconv.Atoi(cid)

			if err != nil {
				p.wrongParameter(&w, err, lang)
				return
			}

			res := p.dbo.tireLifeCircle(iCid, tno)
			buf := p.makeResultBuffer("lifecircles", res)
			w.Write(buf)
		}
	}
}

// 米其林入库信息结构
type MqlStockInT struct {
	Cid     int    `json:"cid"`
	Tid     string `json:"tid"`
	Wid     int    `json:"wid"`
	Brand   string `json:"brand"`
	Model   string `json:"model"`
	Pattern string `json:"pattern"`
	Tno     string `json:"tno"`
	Rfid    string `json:"rfid"`
	Dot     string `json:"dot"`
	Depth   string `json:"depth"`
	Status  int    `json:"status"`
}

// 米其林轮胎入库
func (p *HttpListener) TireMqlStockIn(w http.ResponseWriter, req *http.Request) {
	if lang, userid, ok := p.commonCheck(&w, req); ok {
		req.Header.Set("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept")
		w.Header().Add("Access-Control-Allow-Methods", "POST,GET,OPTIONS,DELETE")

		var sErr string
		var si MqlStockInT

		//读取请求内容
		buf, err := p.readBody(req)
		fmt.Println(string(buf))
		if err == nil {
			err = json.Unmarshal(buf, &si)
		}
		if err != nil {
			sErr = p.makeResultStr2(1009, "参数错误", err.Error(), lang)
			w.Write([]byte(sErr))
			return
		}

		err = p.dbo.tireMqlStockIn(userid, &si)

		if err != nil {
			sErr = p.makeResultStr2(1101, "操作失败", err.Error(), lang)
		} else {
			sErr = p.makeResultStr(0, "", lang)
		}
		w.Write([]byte(sErr))
	}
}

// 轮胎下车
func (p *HttpListener) TireUnload(w http.ResponseWriter, req *http.Request) {
	if lang, userid, ok := p.commonCheck(&w, req); ok {
		cid := req.FormValue("cid")
		tid := req.FormValue("tid")
		wid := req.FormValue("wid")
		rid := req.FormValue("rid")
		vid := req.FormValue("vid")
		cardid := req.FormValue("cardid")
		sn := req.FormValue("sn")
		tno := req.FormValue("tno")
		depths := req.FormValue("depths")
		status := req.FormValue("status")
		ma := req.FormValue("ma")
		reason := req.FormValue("reason")

		if p.checkFields(&w, lang, cid, tno) {
			var err error
			var errStr string
			var iCid, iWid, iStatus, iMa, iCardid, iSn int

			if rid == "" && vid == "" {
				p.wrongParameter(&w, errors.New("Rid/Vid不能同时为空"), lang)
				return
			}

			iCid, err = strconv.Atoi(cid)
			if err == nil {
				iWid, _ = strconv.Atoi(wid)
				iCardid, err = strconv.Atoi(cardid)
				if err == nil {
					iSn, err = strconv.Atoi(sn)
				}
			}

			if err != nil {
				p.wrongParameter(&w, err, lang)
				return
			}

			iStatus, _ = strconv.Atoi(status)
			iMa, _ = strconv.Atoi(ma)

			err = p.dbo.tireUnload(userid, iCid, tid, iWid, rid, vid, iCardid, iSn, tno, depths, iStatus, iMa, reason)
			if err == nil {
				errStr = p.makeResultStr(0, "", lang)
			} else {
				errStr = p.makeResultStr2(1101, "操作失败", err.Error(), lang)
			}

			w.Write([]byte(errStr))
		}
	}
}

// 交换轮位
func (p *HttpListener) TireExchangeTirePosition(w http.ResponseWriter, req *http.Request) {
	if lang, userid, ok := p.commonCheck(&w, req); ok {
		rid := req.FormValue("rid")
		vid := req.FormValue("vid")
		cardid1 := req.FormValue("cardid1")
		sn1 := req.FormValue("sn1")
		tno1 := req.FormValue("tno1")
		cardid2 := req.FormValue("cardid2")
		sn2 := req.FormValue("sn2")
		tno2 := req.FormValue("tno2")
		operator := req.FormValue("operator")
		if operator == "" {
			operator = userid
		}
		opt := req.FormValue("operatetime")

		if p.checkFields(&w, lang, cardid1, sn1, cardid2, sn2, tno1, tno2) {
			if rid == "" && vid == "" {
				p.wrongParameter(&w, errors.New("Rid/Vid不能同时为空"), lang)
				return
			}

			var iCardid1, iSn1, iCardid2, iSn2, iOpt int
			var err error

			iCardid1, err = strconv.Atoi(cardid1)
			if err == nil {
				iSn1, err = strconv.Atoi(sn1)
				if err == nil {
					iCardid2, _ = strconv.Atoi(cardid2)
					iSn2, err = strconv.Atoi(sn2)
				}
			}
			if err != nil {
				p.wrongParameter(&w, err, lang)
				return
			}
			iOpt, err = strconv.Atoi(opt)
			if err != nil {
				iOpt = int(time.Now().Unix())
			}

			err = p.dbo.TireExchangeTirePosition(rid, vid, iCardid1, iSn1, tno1, iCardid2, iSn2, tno2, operator, iOpt)

			var res string

			if err == nil {
				res = p.makeResultStr(0, "", lang)
			} else {
				res = p.makeResultStr2(1101, "操作失败", err.Error(), lang)
			}

			w.Write([]byte(res))
		}
	}
}

// 设置胎纹深度报警的阀值
func (p *HttpListener) TireSetThreshold(w http.ResponseWriter, req *http.Request) {
	if lang, userid, ok := p.commonCheck(&w, req); ok {
		threshold1 := req.FormValue("threshold1")
		threshold2 := req.FormValue("threshold2")

		if p.checkFields(&w, lang, threshold1, threshold2) {
			var err error
			var iThreshold1, iThreshold2 int

			iThreshold1, err = strconv.Atoi(threshold1)
			if err == nil {
				iThreshold2, err = strconv.Atoi(threshold2)
			}

			if err != nil || iThreshold1 == 0 || iThreshold2 == 0 {
				p.wrongParameter(&w, err, lang)
				return
			}

			var sErr string

			p.dbo.tireSetThreshold(userid, iThreshold1, iThreshold2)
			sErr = p.makeResultStr(0, "", "")
			w.Write([]byte(sErr))
		}
	}
}

// 维护时的轮胎信息结构
type MaintainTireInfo struct {
	Brand    string    `bson:"brand" json:"brand"`
	Model    string    `bson:"model" json:"model"`
	Pattern  string    `bson:"pattern" json:"pattern"`
	TireNo   string    `bson:"tireno" json:"tireno"`
	Dot      string    `bson:"dot" json:"dot"`
	Depth    []float64 `bson:"depth" json:"depth"`
	Mileage  int       `bson:"mileage" json:"mileage"`
	Duration int       `bson:"duration" json:"duration"`
}

// 维护信息结构
type MaintainInfo struct {
	Cid          int              `bson:"cid" json:"cid"`
	Company      string           `bson:"company" json:"company"`
	Tid          string           `bson:"tid" json:"tid"`
	Team         string           `bson:"team" json:"team"`
	Rid          string           `bson:"rid" json:"rid"`
	Vid          string           `bson:"vid" json:"vid"`
	Plate        string           `bson:"plate" json:"plate"`
	Driver       string           `bson:"driver" json:"driver"`
	DriverPhone  string           `bson:"dp" json:"dp"`
	Sid          string           `bson:"sid" json:"sid"`
	CardId       int              `bson:"cardid" json:"cardid"`
	Sn           int              `bson:"sn" json:"sn"`
	Position     string           `bson:"position" json:"position"`
	OldTire      MaintainTireInfo `bson:"oldtire" json:"oldtire"`
	NewTire      MaintainTireInfo `bson:"newtire" json:"newtire"`
	MaintainType int              `bson:"mtype" json:"mtype"`       //维护类型
	Exchange     int              `bson:"exchange" json:"exchange"` //轮胎换下方式
	MaintainTime int64            `bson:"mtime" json:"mtime"`
	Cost         float64          `bson:"cost" json:"cost"`       //维护费用
	Comment      string           `bson:"comment" json:"comment"` //备注
	ImgUrl       []string         `bson:"imgurl" json:"imgurl"`   //照片的地址
	Operator     string           `bson:"operator" json:"operator"`
	Address      string           `bson:"address" json:"address"`
}

// 轮胎维修
func (p *HttpListener) TireMaintain(w http.ResponseWriter, req *http.Request) {
	if language, _, ok := p.commonCheck(&w, req); ok {
		mi := MaintainInfo{
			Cid:         0,
			Company:     req.FormValue("company"),
			Tid:         req.FormValue("tid"),
			Team:        req.FormValue("team"),
			Rid:         req.FormValue("rid"),
			Vid:         req.FormValue("vid"),
			Plate:       req.FormValue("plate"),
			Driver:      req.FormValue("driver"),
			DriverPhone: req.FormValue("dp"),
			Sid:         req.FormValue("sid"),
			CardId:      0,
			Sn:          0,
			Position:    req.FormValue("position"),
			OldTire: MaintainTireInfo{
				Brand:   req.FormValue("oldtirebrand"),
				Model:   req.FormValue("oldtiremodel"),
				Pattern: req.FormValue("oldtirepattern"),
				TireNo:  req.FormValue("oldtno"),
				Depth:   []float64{},
			},
			NewTire: MaintainTireInfo{
				Brand:   req.FormValue("newtirebrand"),
				Model:   req.FormValue("newtiremodel"),
				Pattern: req.FormValue("newtirepattern"),
				TireNo:  req.FormValue("newtno"),
				Depth:   []float64{},
			},
			MaintainType: 0,
			Exchange:     0,
			MaintainTime: 0,
			Cost:         0,
			Comment:      req.FormValue("comment"),
			ImgUrl:       nil,
			Operator:     req.FormValue("operator"),
			Address:      req.FormValue("address"),
		}

		cid := req.FormValue("cid")
		cardid := req.FormValue("cardid")
		sn := req.FormValue("sn")
		oldTireDepth := req.FormValue("oldtiredepth")
		oldTireMileage := req.FormValue("oldtiremileage")
		oldTireDuration := req.FormValue("oldtireduration")

		newTireDepth := req.FormValue("newtiredepth")
		newTireMileage := req.FormValue("newtiremileage")
		newTireDuration := req.FormValue("newtireduration")

		maintainType := req.FormValue("maintaintype")
		exchange := req.FormValue("exchange")
		mtime := req.FormValue("mtime")

		cost := req.FormValue("cost")
		imgurl := req.FormValue("imgurl")

		if p.checkFields(&w, language, cid, mi.Rid, mi.Vid, mi.Plate, cardid, sn, mi.Position, mi.NewTire.TireNo,
			maintainType, exchange, mtime, mi.Operator, mi.Address) {
			var err error
			var tempSlice []string
			var tempFloat float64

			mi.Cid, err = strconv.Atoi(cid)
			if err != nil {
				sErr := p.makeResultStr(1009, "参数错误", language)
				w.Write([]byte(sErr))
				return
			}
			mi.CardId, _ = strconv.Atoi(cardid)
			mi.Sn, _ = strconv.Atoi(sn)
			mi.MaintainTime, _ = strconv.ParseInt(mtime, 10, 64)

			//处理旧胎的胎纹深度
			tempSlice = strings.Split(oldTireDepth, ",")
			if len(tempSlice) > 0 {
				for _, v := range tempSlice {
					tempFloat, _ = strconv.ParseFloat(v, 32)
					mi.OldTire.Depth = append(mi.OldTire.Depth, tempFloat)
				}
			}
			//处理新胎的胎纹深度
			tempSlice = strings.Split(newTireDepth, ",")
			if len(tempSlice) > 0 {
				for _, v := range tempSlice {
					tempFloat, _ = strconv.ParseFloat(v, 32)
					mi.NewTire.Depth = append(mi.NewTire.Depth, tempFloat)
				}
			}
			//处理图像地址
			if imgurl != "" {
				if imgurl[len(imgurl)-1] == ',' {
					imgurl = imgurl[:len(imgurl)-1]
				}
			}
			mi.ImgUrl = strings.Split(imgurl, ",")

			mi.OldTire.Mileage, _ = strconv.Atoi(oldTireMileage)
			mi.OldTire.Duration, _ = strconv.Atoi(oldTireDuration)
			mi.NewTire.Mileage, _ = strconv.Atoi(newTireMileage)
			mi.NewTire.Duration, _ = strconv.Atoi(newTireDuration)
			mi.Cost, _ = strconv.ParseFloat(cost, 64)
			mi.MaintainType, _ = strconv.Atoi(maintainType)
			mi.Exchange, _ = strconv.Atoi(exchange)
			mi.MaintainTime, _ = strconv.ParseInt(mtime, 10, 64)

			//total, res := p.dbo.tireList(userid, iCid, tid, tno, iPage)
			p.dbo.tireMaintain(&mi)
			ret := make(map[string]interface{})
			ret["errcode"] = 0

			buf, _ := json.Marshal(ret)
			w.Write(buf)
		}
	}
}

// 查询维修历史列表
func (p *HttpListener) TireMaintainList(w http.ResponseWriter, req *http.Request) {
	if language, _, ok := p.commonCheck(&w, req); ok {
		cid := req.FormValue("cid")
		tid := req.FormValue("tid")
		vid := req.FormValue("vid")
		cardid := req.FormValue("cardid")
		sn := req.FormValue("sn")
		dateStart := req.FormValue("datestart")
		dateEnd := req.FormValue("dateend")
		page := req.FormValue("page")

		if p.checkFields(&w, language, cid) {
			var err error
			var sErr string
			var iCid, iCardId, iSN, iDateStart, iDateEnd, iPage int
			iCid, err = strconv.Atoi(cid)
			if err != nil {
				sErr = p.makeResultStr(1009, "参数错误", language)
				w.Write([]byte(sErr))
				return
			}
			iCardId, err = strconv.Atoi(cardid)
			if err != nil {
				iCardId = -1
			}
			iSN, err = strconv.Atoi(sn)
			if err != nil {
				iSN = -1
			}
			iDateStart, err = strconv.Atoi(dateStart)
			if err != nil {
				iDateStart = -1
			}
			iDateEnd, err = strconv.Atoi(dateEnd)
			if err != nil {
				iDateEnd = -1
			}
			iPage, _ = strconv.Atoi(page)

			total, res, err := p.dbo.tireMaintainList(iCid, tid, vid, iCardId, iSN, iDateStart, iDateEnd, iPage)
			if err != nil {
				sErr = p.makeResultStr2(2000, "查询失败", err.Error(), language)
				w.Write([]byte(sErr))
			} else {
				ret := make(map[string]interface{})
				ret["errcode"] = 0
				ret["total"] = total
				ret["datas"] = res

				buf, _ := json.Marshal(ret)
				w.Write(buf)
			}
		}
	}
}

// 查询维修纪录详情
func (p *HttpListener) TireMaintainDetail(w http.ResponseWriter, req *http.Request) {
	if language, _, ok := p.commonCheck(&w, req); ok {
		id := req.FormValue("id")
		if p.checkFields(&w, language, id) {
			res, err := p.dbo.tireMaintainDetail(id)
			if err != nil {
				sErr := p.makeResultStr2(2000, "查询维修纪录出错,", err.Error(), language)
				w.Write([]byte(sErr))
			} else {
				ret := make(map[string]interface{})
				ret["errcode"] = 0
				ret["data"] = res

				buf, _ := json.Marshal(ret)
				w.Write(buf)
			}
		}
	}
}

/*{
	"cid": 1,
	"tid":"xxxx",
	"tires": [
		{
		"brand":"泰凯英",
		"model":"16.00R25",
		"pattern":"SUPER ETOT",
		"no":"B201207001003",
		"rfid":"0000e200001d170b02352070d8ad",
		"dot":"DOT123456",
		"formula":"C1",
		"factory":"HK",
		"load":"285",
		"depth":32,
		"date":"2021.12.15",
		"operator":"吴云鹏",
		"storeage":"乌海亿兴项目部",
		"status":"旧备胎"
		}
	]
}*/
//轮胎导入数据结构
type TireImprtOneT struct {
	Brand    string  `json:"brand"`
	Model    string  `json:"model"`
	Pattern  string  `json:"pattern"`
	No       string  `json:"no"`
	Rfid     string  `json:"rfid"`
	Dot      string  `json:"dot"`
	Formula  string  `json:"formula"`
	Factory  string  `json:"factory"`
	Load     int     `json:"load"`
	Depth    float32 `json:"depth"` //胎纹深度，单位毫米
	Operator string  `json:"operator"`
	Storeage string  `json:"storeage"`
	Status   string  `json:"status"`
}
type TireImportT struct {
	Cid   int             `json:"cid"`
	Tid   string          `json:"tid"`
	Tires []TireImprtOneT `json:"tires"`
}

// 轮胎批量导入
func (p *HttpListener) TireImport(w http.ResponseWriter, req *http.Request) {
	if language, _, ok := p.commonCheck(&w, req); ok {
		req.Header.Set("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept")
		w.Header().Add("Access-Control-Allow-Methods", "POST,GET,OPTIONS,DELETE")

		var sErr string
		var ti TireImportT

		//读取请求内容
		buf, err := p.readBody(req)
		if err == nil {
			err = json.Unmarshal(buf, &ti)
			if ti.Cid == 0 {
				err = errors.New("无效的Cid")
			} else if ti.Tid != "" {
				//判断该Tid是不是在Cid下面
				if !p.dbo.teamBelongCompay(ti.Cid, ti.Tid) {
					err = errors.New("该车队不属于该公司")
				}
			}
		}
		if err != nil {
			p.wrongParameter(&w, err, language)
			return
		}

		err = p.dbo.tireImport(&ti)

		if err != nil {
			sErr = p.makeResultStr2(1032, "轮胎导入失败", "\r\n"+err.Error(), language)
		} else {
			sErr = p.makeResultStr(0, "", language)
		}
		w.Write([]byte(sErr))
	}
}

// 分配轮胎
func (p *HttpListener) TireAssign(w http.ResponseWriter, req *http.Request) {
	if language, userid, ok := p.commonCheck(&w, req); ok {
		//只有系统管理员和公司管理人员才能够导入
		ut := p.dbo.userType(userid)
		if ut != UserTypeAdministrator && ut != UserTypeSystemUser {
			sErr := p.makeResultStr(1014, "无此权限", language)
			w.Write([]byte(sErr))
			return
		}
		req.ParseForm()

		cid := req.FormValue("cid")
		tid := req.FormValue("tid")
		tnos := req.FormValue("tnos")
		if p.checkFields(&w, language, cid, tid, tnos) {

			var sErr string
			var err error
			var iCid int

			//检查参数合法性
			iCid, err = strconv.Atoi(cid)
			if err != nil || iCid == 0 {
				p.wrongParameter(&w, nil, language)
				return
			}
			if !p.dbo.teamBelongCompay(iCid, tid) {
				p.wrongParameter(&w, nil, language)
				return
			}

			tnoSlice := strings.Split(tnos, ",")
			p.dbo.tireAssign(iCid, tid, tnoSlice)

			sErr = p.makeResultStr(0, "", language)
			w.Write([]byte(sErr))
		}
	}
}

// 传感器管理--------------------------------------------------------------------------
// 传感器最新报警信息
func (p *HttpListener) SensorLastWarning(w http.ResponseWriter, req *http.Request) {
	if language, _, ok := p.commonCheck(&w, req); ok {
		sid := req.FormValue("sid")
		warntypes := req.FormValue("warntypes")
		gpsType := req.FormValue("type")
		if p.checkFields(&w, language, sid, warntypes) {
			if gpsType == "" {
				gpsType = GpsBd09
			}
			res := p.dbo.sensorLastWarning(sid, warntypes, gpsType)
			ret := make(map[string]interface{})
			ret["errcode"] = 0
			ret["datas"] = res

			buf, _ := json.Marshal(ret)
			w.Write(buf)
		}
	}
}

// 场站管理----------------------------------------------------------------------------
// 场站列表
func (p *HttpListener) MaintenanceSiteList(w http.ResponseWriter, req *http.Request) {
	if language, userid, ok := p.commonCheck(&w, req); ok {
		cid := req.FormValue("cid")
		tid := req.FormValue("tid")
		name := req.FormValue("name")
		address := req.FormValue("address")
		page := req.FormValue("page")
		count := req.FormValue("count")

		if p.checkFields(&w, language, cid) {
			var err error
			var iCid, iPage, iCount int

			iCid, err = strconv.Atoi(cid)
			if err != nil {
				sErr := p.makeResultStr(1009, "参数错误", language)
				w.Write([]byte(sErr))
				return
			}

			iPage, err = strconv.Atoi(page)
			if err != nil {
				iPage = 0
			}

			iCount, err = strconv.Atoi(count)
			if err != nil {
				iCount = 10
			}

			res, total, err := p.dbo.maintenanceSiteList(userid, iCid, tid, name, address, iPage, iCount)
			if err != nil {
				sErr := p.makeResultStr2(2000, "数据查询失败", err.Error(), language)
				w.Write([]byte(sErr))
				return
			} else {
				ret := make(map[string]interface{})
				ret["errcode"] = 0
				ret["total"] = total
				ret["datas"] = res

				buf, _ := json.Marshal(ret)
				w.Write(buf)
			}
		}
	}
}

// 新增场站
func (p *HttpListener) MaintenanceSiteAdd(w http.ResponseWriter, req *http.Request) {
	if language, _, ok := p.commonCheck(&w, req); ok {
		cid := req.FormValue("cid")
		tid := req.FormValue("tid")
		name := req.FormValue("name")
		address := req.FormValue("address")
		lng := req.FormValue("lng")
		lat := req.FormValue("lat")
		contacts := req.FormValue("contacts")
		phone := req.FormValue("phone")
		workers := req.FormValue("workers")
		wdbegin := req.FormValue("wdbegin")
		wdend := req.FormValue("wdend")
		wtbegin := req.FormValue("wtbegin")
		wtend := req.FormValue("wtend")
		public := req.FormValue("public")
		level := req.FormValue("level")
		remark := req.FormValue("remark")

		if p.checkFields(&w, language, cid, name, address, lng, lat) {
			var iCid int
			var fLng, fLat float64
			var iWdBegin, iWdEnd, iWtBegin, iWtEnd int
			var err error
			var sErr string
			var bPublic bool
			var iLevel int

			iCid, err = strconv.Atoi(cid)
			if err == nil {
				fLng, err = strconv.ParseFloat(lng, 64)
				if err == nil {
					fLat, err = strconv.ParseFloat(lat, 64)
				}
			}
			if err != nil {
				sErr = p.makeResultStr(1009, "参数错误", language)
				w.Write([]byte(sErr))
				return
			}
			iWdBegin, _ = strconv.Atoi(wdbegin)
			iWdEnd, _ = strconv.Atoi(wdend)
			iWtBegin, _ = strconv.Atoi(wtbegin)
			iWtEnd, _ = strconv.Atoi(wtend)
			if public == "" {
				bPublic = false
			} else {
				bPublic, err = strconv.ParseBool(public)
				if err != nil {
					bPublic = false
				}
			}
			iLevel, err = strconv.Atoi(level)
			if err != nil {
				iLevel = 0
			}

			ms := MaintenanceSiteT{
				Oid:      bson.NewObjectId(),
				Cid:      iCid,
				Tid:      tid,
				Name:     name,
				Address:  address,
				Location: MaintenanceSiteLocationT{Lng: fLng, Lat: fLat},
				Contacts: contacts,
				Phone:    phone,
				//WorkerArray:   strings.Split(workers, ","),
				WorkDayBegin:  iWdBegin,
				WorkDayEnd:    iWdEnd,
				WorkTimeBegin: iWtBegin,
				WorkTimeEnd:   iWtEnd,
				Public:        bPublic,
				Level:         iLevel,
				Remark:        remark,
			}
			if workers != "" {
				ms.WorkerArray = strings.Split(workers, ",")
			}
			err = p.dbo.maintenanceSiteAdd(&ms)
			if err != nil {
				sErr = p.makeResultStr2(1101, "操作失败", err.Error(), language)
				w.Write([]byte(sErr))
				return
			}

			ret := map[string]interface{}{
				"errcode": 0,
				"id":      ms.Oid.Hex(),
			}
			buf, _ := json.Marshal(ret)
			w.Write(buf)
		}
	}
}

// 修改场站信息
func (p *HttpListener) MaintenanceSiteEdit(w http.ResponseWriter, req *http.Request) {
	if language, _, ok := p.commonCheck(&w, req); ok {
		id := req.FormValue("id")
		name := req.FormValue("name")
		address := req.FormValue("address")
		lng := req.FormValue("lng")
		lat := req.FormValue("lat")
		contacts := req.FormValue("contacts")
		phone := req.FormValue("phone")
		workers := req.FormValue("workers")
		wdbegin := req.FormValue("wdbegin")
		wdend := req.FormValue("wdend")
		wtbegin := req.FormValue("wtbegin")
		wtend := req.FormValue("wtend")
		public := req.FormValue("public")
		level := req.FormValue("level")
		remark := req.FormValue("remark")

		if p.checkFields(&w, language, id) {
			var sErr string

			if name == "" && address == "" && lng == "" && lat == "" && contacts == "" &&
				phone == "" && workers == "" && wdbegin == "" && wdend == "" && wtbegin == "" && wtend == "" && public == "" {
				sErr = p.makeResultStr(1009, "参数错误", language)
				w.Write([]byte(sErr))
				return
			}

			if !bson.IsObjectIdHex(id) {
				sErr = p.makeResultStr(1009, "参数错误", language)
				w.Write([]byte(sErr))
				return
			}

			var fLng, fLat float64
			var iWdBegin, iWdEnd, iWtBegin, iWtEnd, iLevel int
			var err error
			var bPublic bool

			fLng, _ = strconv.ParseFloat(lng, 64)
			fLat, _ = strconv.ParseFloat(lat, 64)
			iWdBegin, _ = strconv.Atoi(wdbegin)
			iWdEnd, _ = strconv.Atoi(wdend)
			iWtBegin, _ = strconv.Atoi(wtbegin)
			iWtEnd, _ = strconv.Atoi(wtend)
			if public == "" {
				bPublic = false
			} else {
				bPublic, err = strconv.ParseBool(public)
				if err != nil {
					bPublic = false
				}
			}
			iLevel, err = strconv.Atoi(level)
			if err != nil {
				iLevel = 0
			}

			ms := MaintenanceSiteT{
				Id:            id,
				Name:          name,
				Address:       address,
				Location:      MaintenanceSiteLocationT{Lng: fLng, Lat: fLat},
				Contacts:      contacts,
				Phone:         phone,
				WorkDayBegin:  iWdBegin,
				WorkDayEnd:    iWdEnd,
				WorkTimeBegin: iWtBegin,
				WorkTimeEnd:   iWtEnd,
				Public:        bPublic,
				Level:         iLevel,
				Remark:        remark,
			}
			if workers != "" {
				ms.WorkerArray = strings.Split(workers, ",")
			}
			err = p.dbo.maintenanceSiteEdit(&ms)
			if err != nil {
				sErr = p.makeResultStr2(1101, "操作失败", err.Error(), language)
				w.Write([]byte(sErr))
				return
			}

			sErr = p.makeResultStr(0, "", language)
			w.Write([]byte(sErr))
		}
	}
}

// 删除场站
func (p *HttpListener) MaintenanceSiteRemove(w http.ResponseWriter, req *http.Request) {
	if language, _, ok := p.commonCheck(&w, req); ok {
		id := req.FormValue("id")

		if p.checkFields(&w, language, id) {
			var sErr string

			if !bson.IsObjectIdHex(id) {
				sErr = p.makeResultStr(1009, "参数错误", language)
				w.Write([]byte(sErr))
				return
			}

			err := p.dbo.maintenanceSiteRemove(id)
			if err != nil {
				sErr = p.makeResultStr2(1101, "操作失败", err.Error(), language)
				w.Write([]byte(sErr))
				return
			}

			sErr = p.makeResultStr(0, "", language)
			w.Write([]byte(sErr))
		}
	}
}

// 查找附近场站
func (p *HttpListener) MaintenanceSiteNear(w http.ResponseWriter, req *http.Request) {
	if language, _, ok := p.commonCheck(&w, req); ok {
		cid := req.FormValue("cid")
		tid := req.FormValue("tid")
		lng := req.FormValue("lng")
		lat := req.FormValue("lat")
		radius := req.FormValue("radius")
		count := req.FormValue("count")
		gpsType := req.FormValue("gpstype")
		gpsTypeR := req.FormValue("gpstyper")

		if p.checkFields(&w, language, cid, lng, lat) {
			var sErr string
			var fLng, fLat float64
			var iCid, iCount, iRadius int
			var err error

			iCid, err = strconv.Atoi(cid)
			if err == nil {
				fLng, err = strconv.ParseFloat(lng, 64)
				if err == nil {
					fLat, err = strconv.ParseFloat(lat, 64)
				}
			}

			if err != nil {
				sErr = p.makeResultStr(1009, "参数错误", language)
				w.Write([]byte(sErr))
				return
			}

			iRadius, err = strconv.Atoi(radius)
			if err != nil {
				//默认半径10公里
				iRadius = 10000
			}

			iCount, err = strconv.Atoi(count)
			if err != nil {
				//返回纪录数默认10条
				iCount = 10
			}

			if gpsType != GpsBd09 && gpsType != GpsGCJ02 && gpsType != GpsWGS84 {
				gpsType = GpsBd09
			}
			if gpsTypeR != GpsBd09 && gpsTypeR != GpsGCJ02 && gpsTypeR != GpsWGS84 {
				gpsTypeR = GpsBd09
			}

			var g gps.GPS
			//坐标系统需要转换成百度坐标系统
			if gpsType == GpsGCJ02 {
				fLat, fLng = g.BDEncrypt(fLat, fLng)
			} else if gpsType == GpsWGS84 {
				fLat, fLng = g.TransformFromWGSToGCJ(fLat, fLng)
				fLat, fLng = g.BDEncrypt(fLat, fLng)
			}

			sites := p.dbo.maintenanceSiteNear(iCid, tid, fLng, fLat, iRadius, iCount)

			//结果数据为百度坐标系统，需要转换为目标坐标系统
			if gpsTypeR != GpsBd09 {
				for i := 0; i < len(sites); i++ {
					sites[i].Location.Lat, sites[i].Location.Lng = g.BDDecrypt(sites[i].Location.Lat, sites[i].Location.Lng)

					if gpsTypeR == GpsWGS84 {
						sites[i].Location.Lat, sites[i].Location.Lng = g.TransformFromWGSToGCJ(sites[i].Location.Lat, sites[i].Location.Lng)
					}
				}
			}

			buf := p.makeResultBuffer("sites", sites)

			w.Write(buf)
		}
	}
}

// 仓库管理----------------------------------------------------------------------------
// 仓库查询
func (p *HttpListener) WareHouseList(w http.ResponseWriter, req *http.Request) {
	if language, userid, ok := p.commonCheck(&w, req); ok {
		req.ParseForm()

		cid := req.FormValue("cid")
		tid := req.FormValue("tid")
		name := req.FormValue("name")
		address := req.FormValue("address")
		page := req.FormValue("page")

		if p.checkFields(&w, language, cid) {
			iPage, err := strconv.Atoi(page)
			if err != nil {
				iPage = 0
			}

			iCid, err := strconv.Atoi(cid)
			if err != nil {
				sErr := p.makeResultStr(1009, "参数错误", language)
				w.Write([]byte(sErr))
			}

			//非系统管理员不能查询全部数据
			userType := p.dbo.userType(userid)
			if userType != UserTypeSystemUser && iCid == 0 {
				buf := p.makeResultBuffer("warehouses", nil)
				w.Write(buf)
				return
			}

			count, res, err := p.dbo.warehouseList(iCid, tid, name, address, iPage)
			if err != nil {
				sErr := p.makeResultStr(2001, "数据查询无结果", language)
				w.Write([]byte(sErr))
			} else {
				ret := make(map[string]interface{})
				ret["errcode"] = 0
				ret["count"] = count
				ret["warehouses"] = res

				buf, _ := json.Marshal(ret)
				w.Write(buf)
			}
		}
	}
}

// 新增仓库
func (p *HttpListener) WareHouseAdd(w http.ResponseWriter, req *http.Request) {
	if lang, _, ok := p.commonCheck(&w, req); ok {
		req.ParseForm()

		cid := req.FormValue("cid")
		tid := req.FormValue("tid")
		name := req.FormValue("name")
		address := req.FormValue("address")
		manager := req.FormValue("manager")
		phone := req.FormValue("phone")

		var iCid int
		var err error
		var sErr string
		var wid int64

		if p.checkFields(&w, lang, cid, name, address) {
			iCid, err = strconv.Atoi(cid)
			if err != nil {
				sErr = p.makeResultStr(1009, "参数错误", lang)
				w.Write([]byte(sErr))
				return
			}

			wid, err = p.dbo.warehouseAdd(iCid, tid, name, address, manager, phone)
			if err != nil {
				sErr = p.makeResultStr2(1101, "操作失败", err.Error(), lang)
				w.Write([]byte(sErr))
			} else {
				ret := make(map[string]interface{})
				ret["errcode"] = 0
				ret["wid"] = wid
				buf, _ := json.Marshal(ret)
				w.Write(buf)
			}

			return
		}
	}
}

// 修改仓库信息
func (p *HttpListener) WareHouseEdit(w http.ResponseWriter, req *http.Request) {
	if lang, _, ok := p.commonCheck(&w, req); ok {
		req.ParseForm()

		wid := req.FormValue("wid")
		cid := req.FormValue("cid")
		tid := req.FormValue("tid")
		name := req.FormValue("name")
		address := req.FormValue("address")
		manager := req.FormValue("manager")
		phone := req.FormValue("phone")

		var iCid int
		var iWid int
		var err error
		var sErr string

		if p.checkFields(&w, lang, wid, cid) {
			iCid, err = strconv.Atoi(cid)
			if err == nil {
				iWid, err = strconv.Atoi(wid)
			}
			if err != nil {
				sErr = p.makeResultStr(1009, "参数错误", lang)
				w.Write([]byte(sErr))
				return
			}

			err = p.dbo.warehouseEdit(iWid, iCid, tid, name, address, manager, phone)
			if err != nil {
				sErr = p.makeResultStr2(1101, "操作失败", err.Error(), lang)
			} else {
				sErr = p.makeResultStr(0, "", lang)
			}
			w.Write([]byte(sErr))

			return
		}
	}
}

// 删除指定仓库纪录
func (p *HttpListener) WareHouseDelete(w http.ResponseWriter, req *http.Request) {
	if lang, _, ok := p.commonCheck(&w, req); ok {
		req.ParseForm()

		var sErr string

		wid := req.FormValue("wid")
		if p.checkFields(&w, lang, wid) {
			iWid, err := strconv.Atoi(wid)
			if err != nil {
				sErr = p.makeResultStr(1009, "参数错误", lang)
				w.Write([]byte(sErr))
				return
			}

			p.dbo.warehouseDelete(iWid)
			sErr = p.makeResultStr(0, "", lang)
			w.Write([]byte(sErr))
		}
	}
}

// 里程统计----------------------------------------------------------------------------
// 传感器里程
func (p *HttpListener) MileageSensor(w http.ResponseWriter, req *http.Request) {
	if language, _, ok := p.commonCheck(&w, req); ok {
		sid := req.FormValue("sid")

		if p.checkFields(&w, language, sid) {

			res := p.dbo.mileageSensor(sid)
			ret := make(map[string]interface{})
			ret["errcode"] = 0
			ret["mileage"] = res

			buf, _ := json.Marshal(ret)
			w.Write(buf)
		}
	}
}

// 里程统计
func (p *HttpListener) MileageStatistics(w http.ResponseWriter, req *http.Request) {
	if language, _, ok := p.commonCheck(&w, req); ok {
		cid := req.FormValue("cid")
		tid := req.FormValue("tid")
		rid := req.FormValue("rid")
		year := req.FormValue("year")
		month := req.FormValue("month")

		var iCid, iYear, iMonth int
		var err error
		var sErr string

		if cid == "" {
			iCid = 0
		} else {
			iCid, err = strconv.Atoi(cid)
			if err != nil {
				sErr = p.makeResultStr(1009, "参数错误", language)
				w.Write([]byte(sErr))
				return
			}
		}
		if year == "" {
			iYear = 0
		} else {
			iYear, err = strconv.Atoi(year)
			if err != nil {
				sErr = p.makeResultStr(1009, "参数错误", language)
				w.Write([]byte(sErr))
				return
			}
		}
		if month == "" {
			iMonth = 0
		} else {
			iMonth, err = strconv.Atoi(month)
			if err != nil {
				sErr = p.makeResultStr(1009, "参数错误", language)
				w.Write([]byte(sErr))
				return
			}
		}

		ret := make(map[string]interface{})
		res, err := p.dbo.mileageStatistics(iCid, tid, rid, iYear, iMonth)
		if err != nil {
			ret["errcode"] = 1009
			ret["msg"] = err.Error()
		} else {
			ret["errcode"] = 0
			ret["data"] = res
		}

		buf, _ := json.Marshal(ret)
		w.Write(buf)
	}
}

// 里程报表
func (p *HttpListener) ReportMillage(w http.ResponseWriter, req *http.Request) {
	if language, userid, ok := p.commonCheck(&w, req); ok {
		cid := req.FormValue("cid")
		tid := req.FormValue("tid")
		rid := req.FormValue("rid")
		begindate := req.FormValue("begindate")
		enddate := req.FormValue("enddate")
		page := req.FormValue("page")

		if p.checkFields(&w, language, cid, begindate, enddate) {
			var iCid, iBeginDate, iEndDate, iPage int
			var err error
			var sErr string

			iCid, err = strconv.Atoi(cid)
			if err == nil {
				iBeginDate, err = strconv.Atoi(begindate)
				if err == nil {
					iEndDate, err = strconv.Atoi(enddate)
					if err == nil {
						iPage, err = strconv.Atoi(page)
						if err != nil {
							iPage = 0
							err = nil
						}
					}
				}
			}
			if err != nil {
				sErr = p.makeResultStr(1009, "参数错误", language)
				w.Write([]byte(sErr))
				return
			}
			ret := make(map[string]interface{})
			if iBeginDate > 20000000 {
				iBeginDate -= 20000000
			}
			if iEndDate > 20000000 {
				iEndDate -= 20000000
			}
			total, res, err := p.dbo.reportMileage(userid, iCid, tid, rid, iBeginDate, iEndDate, iPage)
			if err != nil {
				ret["errcode"] = 1009
				ret["msg"] = err.Error()
			} else {
				ret["errcode"] = 0
				ret["total"] = total
				ret["datas"] = res
			}

			buf, _ := json.Marshal(ret)
			w.Write(buf)
		}
	}
}

// 报警报表
func (p *HttpListener) ReportWarning(w http.ResponseWriter, req *http.Request) {
	if language, userid, ok := p.commonCheck(&w, req); ok {
		cid := req.FormValue("cid")
		tid := req.FormValue("tid")
		rid := req.FormValue("rid")
		begindate := req.FormValue("begindate")
		enddate := req.FormValue("enddate")
		warntype := req.FormValue("warntype")
		repeat := req.FormValue("repeat")
		page := req.FormValue("page")

		if p.checkFields(&w, language, cid, begindate, enddate) {
			var iCid, iBeginDate, iEndDate, iPage, iWarnType, iRepeat int
			var err error
			var sErr string

			iWarnType, err = strconv.Atoi(warntype)
			if err != nil {
				iWarnType = 0
			}
			iRepeat, err = strconv.Atoi(repeat)
			if err != nil {
				iRepeat = 0
			}
			iPage, err = strconv.Atoi(page)
			if err != nil {
				iPage = 0
			}

			iCid, err = strconv.Atoi(cid)
			if err == nil {
				iBeginDate, err = strconv.Atoi(begindate)
				if err == nil {
					iEndDate, err = strconv.Atoi(enddate)
				}
			}
			if err != nil {
				sErr = p.makeResultStr(1009, "参数错误", language)
				w.Write([]byte(sErr))
				return
			}
			ret := make(map[string]interface{})
			if iBeginDate > 20000000 {
				iBeginDate -= 20000000
			}
			if iEndDate > 20000000 {
				iEndDate -= 20000000
			}
			total, res, err := p.dbo.reportWarning(userid, iCid, tid, rid, iBeginDate, iEndDate, iWarnType, iRepeat, iPage)
			if err != nil {
				ret["errcode"] = 1009
				ret["msg"] = err.Error()
			} else {
				ret["errcode"] = 0
				ret["total"] = total
				ret["datas"] = res
			}

			buf, _ := json.Marshal(ret)
			w.Write(buf)
		}
	}
}

// 异常运行情况统计
func (p *HttpListener) ReportAbnormalOperation(w http.ResponseWriter, req *http.Request) {
	if language, userid, ok := p.commonCheck(&w, req); ok {
		cid := req.FormValue("cid")
		tid := req.FormValue("tid")
		rid := req.FormValue("rid")
		begindate := req.FormValue("begindate")
		enddate := req.FormValue("enddate")
		warntype := req.FormValue("warntype")
		page := req.FormValue("page")

		if p.checkFields(&w, language, cid, begindate, enddate) {
			var iCid, iBeginDate, iEndDate, iPage, iWarnType int
			var err error
			var sErr string

			iWarnType, err = strconv.Atoi(warntype)
			if err != nil {
				iWarnType = 0
			}
			iPage, err = strconv.Atoi(page)
			if err != nil {
				iPage = 0
			}

			iCid, err = strconv.Atoi(cid)
			if err == nil {
				iBeginDate, err = strconv.Atoi(begindate)
				if err == nil {
					iEndDate, err = strconv.Atoi(enddate)
				}
			}
			if err != nil {
				sErr = p.makeResultStr(1009, "参数错误", language)
				w.Write([]byte(sErr))
				return
			}
			ret := make(map[string]interface{})
			if iBeginDate > 20000000 {
				iBeginDate -= 20000000
			}
			if iEndDate > 20000000 {
				iEndDate -= 20000000
			}
			total, res, err := p.dbo.reportAbnormalOperation(userid, iCid, tid, rid, iBeginDate, iEndDate, iWarnType, iPage)
			if err != nil {
				ret["errcode"] = 1009
				ret["msg"] = err.Error()
			} else {
				ret["errcode"] = 0
				ret["total"] = total
				ret["datas"] = res
			}

			buf, _ := json.Marshal(ret)
			w.Write(buf)
		}
	}
}

// 工作时间统计
func (p *HttpListener) ReportWorkTime(w http.ResponseWriter, req *http.Request) {

	if language, _, ok := p.commonCheck(&w, req); ok {
		cids := req.FormValue("cids")
		tids := req.FormValue("tids")
		begindate := req.FormValue("begindate")
		enddate := req.FormValue("enddate")

		if p.checkFields(&w, language, begindate, enddate) {
			var iBeginDate, iEndDate int
			var err error
			var sErr string
			var res []WorkTimeT

			iBeginDate, err = strconv.Atoi(begindate)
			if err == nil {
				iEndDate, err = strconv.Atoi(enddate)
			}
			if err != nil {
				sErr = p.makeResultStr(1009, "参数错误", language)
				w.Write([]byte(sErr))
				return
			}
			ret := make(map[string]interface{})
			if iBeginDate > 20000000 {
				iBeginDate -= 20000000
			}
			if iEndDate > 20000000 {
				iEndDate -= 20000000
			}
			sliceCid := strings.Split(cids, ",")
			sliceTid := strings.Split(tids, ",")
			res, err = p.dbo.reportWorkTime(sliceCid, sliceTid, iBeginDate, iEndDate)

			if err != nil {
				ret["errcode"] = 1009
				ret["msg"] = err.Error()
			} else {
				ret["errcode"] = 0
				ret["datas"] = res
			}

			buf, _ := json.Marshal(ret)
			w.Write(buf)
		}
	}
}

// 指令下发类函数----------------------------------------------------------------------------
// 下发指令查询
func (p *HttpListener) CommandList(w http.ResponseWriter, req *http.Request) {
	if language, userid, ok := p.commonCheck(&w, req); ok {
		//只有系统管理员才能够操作
		if p.checkUserType(&w, language, userid) {
			req.ParseForm()

			rid := req.FormValue("rid")
			msgType := req.FormValue("type")
			stat := req.FormValue("stat")
			result := req.FormValue("result")
			page := req.FormValue("page")

			var err error
			var iStat, iResult, iPage int

			iStat, err = strconv.Atoi(stat)
			if err != nil {
				iStat = 9
			}
			iResult, err = strconv.Atoi(result)
			if err != nil {
				iResult = 9
			}
			iPage, err = strconv.Atoi(page)
			if err != nil {
				iPage = 0
			}

			total, res := p.dbo.commandList(rid, msgType, iStat, iResult, iPage)
			ret := make(map[string]interface{})
			ret["errcode"] = 0
			ret["total"] = total
			ret["datas"] = res

			buf, _ := json.Marshal(ret)
			w.Write(buf)
		}
	}
}

// 设备安装维护类----------------------------------------------------------------------------
// 新装车辆数据结构
type InstallVehicleDataT struct {
	Rid   string
	Type  int
	Cards []struct {
		CardId int
		Tires  []struct {
			Sn  int
			Sid string `json:"sensortxt"`
		}
	}
}

// 安装新设备
func (p *HttpListener) MaintainInstall(w http.ResponseWriter, req *http.Request) {
	if language, userid, ok := p.commonCheck(&w, req); ok {
		req.Header.Set("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept")
		w.Header().Add("Access-Control-Allow-Methods", "POST,GET,OPTIONS,DELETE")

		rid := req.FormValue("rid")
		sType := req.FormValue("type")
		operator := req.FormValue("operator")
		address := req.FormValue("address")
		data := req.FormValue("data")

		if p.checkFields(&w, language, rid, sType, address, data) {
			var ivd InstallVehicleDataT
			var err error
			var errMsg string
			var iType int

			//车辆类型
			iType, err = strconv.Atoi(sType)
			if err != nil {
				errMsg = p.makeResultStr2(1031, "车辆类型不正确", err.Error(), language)
				w.Write([]byte(errMsg))
				return
			}

			//检测data是不是正确的json格式
			err = json.Unmarshal([]byte(data), &ivd)
			if err != nil {
				errMsg = p.makeResultStr2(1030, "装车数据格式错误", err.Error(), language)
				w.Write([]byte(errMsg))
				return
			}

			//安装信息先保存到数据库中
			p.dbo.maintainInstall(rid, iType, userid, operator, address, data)

			//下发对码
			rbs := ReceiverBindSensorT{}
			rbs.Rid = rid
			rbs.RType = iType
			rbs.Sensors = make([]BindSensorT, 0)
			for _, card := range ivd.Cards {
				for _, sensor := range card.Tires {
					if sensor.Sid != "" {
						bs := BindSensorT{CardId: card.CardId, Sid: sensor.Sid, SN: sensor.Sn}
						rbs.Sensors = append(rbs.Sensors, bs)
					}
				}
			}
			if len(rbs.Sensors) > 0 {
				//如果有传感器信息，则下发对码
				buf, _ := json.Marshal(rbs)

				//设置设备类别
				go p.dbo.setReceiverType(rbs.Rid, rbs.RType)
				//重置关联关系、最新状态信息
				go p.dbo.resetReceiverSensors(rbs.Rid, rbs.Sensors)

				buf, err = p.Post(p.cfg.ReceiverdURL+"/receiver/bindsensor", "", buf)
				if err != nil {
					sErr := p.makeResultStr(1101, err.Error(), language)
					w.Write([]byte(sErr))
				} else {
					w.Write(buf)
				}
				return
			}

			errMsg = p.makeResultStr(0, "", language)
			w.Write([]byte(errMsg))
		}
	}
}

// 新装车辆列表
func (p *HttpListener) MaintainInstallList(w http.ResponseWriter, req *http.Request) {
	if _, userid, ok := p.commonCheck(&w, req); ok {
		cid := req.FormValue("cid")
		tid := req.FormValue("tid")
		rid := req.FormValue("rid")
		sDate := req.FormValue("date")
		stat := req.FormValue("stat")
		page := req.FormValue("page")

		var err error
		var iCid, iDate, iStat, iPage int

		iCid, err = strconv.Atoi(cid)
		if err != nil {
			iCid = 0
		}
		iPage, err = strconv.Atoi(page)
		if err != nil {
			iPage = 0
		}
		iStat, err = strconv.Atoi(stat)
		if err != nil {
			iStat = 0
		}
		iDate, err = strconv.Atoi(sDate)
		if err != nil {
			iDate = 0
		}

		total, el := p.dbo.maintainInstallList(userid, iCid, tid, rid, iDate, iStat, iPage)

		res := make(map[string]interface{})
		res["errcode"] = 0
		res["total"] = total
		res["datas"] = el

		var buf []byte
		buf, _ = json.Marshal(res)
		w.Write(buf)
	}
}

// 新装车辆详情
func (p *HttpListener) MaintainInstallInfo(w http.ResponseWriter, req *http.Request) {
	if language, _, ok := p.commonCheck(&w, req); ok {
		id := req.FormValue("id")

		if p.checkFields(&w, language, id) {
			var err error
			var ei *EquipmentInstallT

			if !bson.IsObjectIdHex(id) {
				msg := p.makeResultStr(1009, "参数错误", language)
				w.Write([]byte(msg))
				return
			}

			ei, err = p.dbo.maintainInstallInfo(id)

			if err != nil {
				msg := p.makeResultStr2(2000, "查询失败", err.Error(), language)
				w.Write([]byte(msg))
				return
			}

			res := make(map[string]interface{})
			res["errcode"] = 0
			res["data"] = ei

			var buf []byte
			buf, _ = json.Marshal(res)
			w.Write(buf)
		}
	}
}

// 车辆巡检数据结构
type MaintainCheckT struct {
	Rid   string `bson:"rid"`
	Vid   string `bson:"vid"`
	Datas []struct {
		Cardid int       `bson:"cardid"`
		Sn     int       `bson:"sn"`
		Sid    string    `bson:"sid"`
		Tno    string    `bson:"tno"`
		Depth  []float32 `bson:"depth"`
	} `bson:"datas"`
	OperatorId string `bson:"operatorid"`
	Operator   string `bson:"operator"`
	Address    string `bson:"address"`
	T          int64  `bson:"t"`
	Date       int    `bson:"date"`
	Time       int    `bson:"time"`
}

// 提交车辆巡检数据
func (p *HttpListener) MaintainCheck(w http.ResponseWriter, req *http.Request) {
	if language, _, ok := p.commonCheck(&w, req); ok {
		req.Header.Set("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept")
		w.Header().Add("Access-Control-Allow-Methods", "POST,GET,OPTIONS,DELETE")

		var sErr string
		var mc MaintainCheckT

		//读取请求内容
		buf, err := p.readBody(req)
		if err == nil {
			err = json.Unmarshal(buf, &mc)
		}
		if err != nil {
			sErr = p.makeResultStr2(1009, "参数错误", err.Error(), language)
			w.Write([]byte(sErr))
			return
		}

		mc.T = time.Now().Unix()
		mc.Date, mc.Time = TimeToIntDateTime(time.Now())
		err = p.dbo.maintainCheck(&mc)

		if err != nil {
			sErr = p.makeResultStr2(1032, "提交失败", err.Error(), language)
		} else {
			sErr = p.makeResultStr(0, "", language)
		}
		w.Write([]byte(sErr))
	}
}

type WorkOrderItemT struct {
	Cardid  int      `json:"cardid" bson:"cardid"`
	Sn      int      `json:"sn" bson:"sn"`
	Item    int      `json:"item" bson:"item"`
	Fault   int      `json:"fault" bson:"fault"`
	OldTno  string   `json:"oldtno" bson:"oldtno"`
	NewTno  string   `json:"newtno" bson:"newtno"`
	HasData int      `json:"hasdata" bson:"hasdata"`
	Reason  string   `json:"reason" bson:"reason"`
	Pics    []string `json:"pics" bson:"pics"`
}
type WorkOrderT struct {
	Cid         int              `json:"cid" bson:"cid"`
	Tid         string           `json:"tid" bson:"tid"`
	Tids        []string         `bson:"tids"`
	Team        string           `json:"team" bson:"team"`
	Date        int              `json:"date" bson:"date"`
	Rid         string           `json:"rid" bson:"rid"`
	Plate       string           `json:"plate" bson:"plate"`
	Driver      string           `json:"driver" bson:"driver"`
	Source      int              `json:"source" bson:"source"`
	Records     []WorkOrderItemT `json:"records" bson:"records"`
	ServiceAddr string           `json:"serviceaddr" bson:"serviceaddr"`
	TireWorker  string           `json:"tireworker" bson:"tireworker"`
	Receipt     int              `json:"receipt" bson:"receipt"`
	Pay         int              `json:"pay" bson:"pay"`
	Cost        float64          `json:"cost" bson:"cost"`
	ExtCost     float64          `json:"extcost" bson:"extcost"`
	Operator    string           `json:"operator" bson:"operator"`
	Uid         string           `json:"uid" bson:"uid"`
	Status      int              `json:"status" bson:"status"`
	Remark      string           `json:"remark" bson:"remark"`
}

func (p *WorkOrderT) FromFixTire(data *MaintainFixTireT) {
	p.Cid, p.Tid, p.Tids = data.Cid, data.Tid, data.Tids
	p.Team = ""
	p.Date = data.Date
	p.Rid = data.Rid
	p.Plate = ""
	p.Source = 5
	p.ServiceAddr = data.Address
	p.TireWorker = data.Operator
	p.Receipt = 0
	p.Pay = 0
	p.Cost = data.Cost
	p.ExtCost = 0.0
	p.Operator = data.Operator
	p.Uid = data.Uid
	p.Status = 0
	p.Remark = data.Remark
	woi := WorkOrderItemT{
		Cardid:  data.CardId,
		Sn:      data.Sn,
		Item:    1,
		Fault:   7,
		OldTno:  data.Tno,
		NewTno:  "",
		HasData: 0,
		Reason:  "",
		Pics:    data.Images,
	}
	p.Records = append(p.Records, woi)
}

func (p *WorkOrderT) FromExchangeTire(data *MaintainExchangeTireT) {
	p.Cid, p.Tid, p.Tids = data.Cid, data.Tid, data.Tids
	p.Team = ""
	p.Date = data.Date
	p.Rid = data.Rid
	p.Plate = ""
	p.Source = 6
	p.ServiceAddr = data.Address
	p.TireWorker = data.Operator
	p.Receipt = 0
	p.Pay = 0
	p.Cost = data.Cost
	p.ExtCost = 0.0
	p.Operator = data.Operator
	p.Uid = data.Uid
	p.Status = 0
	p.Remark = data.Remark
	woi := WorkOrderItemT{
		Cardid:  data.CardId,
		Sn:      data.Sn,
		Item:    2,
		Fault:   7,
		OldTno:  data.Tno,
		NewTno:  data.NewTire.Tno,
		HasData: 0,
		Reason:  "",
		Pics:    data.Images,
	}
	p.Records = append(p.Records, woi)
}

func (p *WorkOrderT) FromFixValve(data *MaintainFixValveT) {
	p.Cid, p.Tid, p.Tids = data.Cid, data.Tid, data.Tids
	p.Team = ""
	p.Date = data.Date
	p.Rid = data.Rid
	p.Plate = ""
	p.Source = 7
	p.ServiceAddr = data.Address
	p.TireWorker = data.Operator
	p.Receipt = 0
	p.Pay = 0
	p.Cost = data.Cost
	p.ExtCost = 0.0
	p.Operator = data.Operator
	p.Uid = data.Uid
	p.Status = 0
	p.Remark = data.Remark
	woi := WorkOrderItemT{
		Cardid:  data.CardId,
		Sn:      data.Sn,
		Item:    9,
		Fault:   7,
		OldTno:  data.Tno,
		NewTno:  "",
		HasData: 0,
		Reason:  "",
		Pics:    data.Images,
	}
	p.Records = append(p.Records, woi)
}

func (p *WorkOrderT) FromInflate(data *MaintainInflateT) {
	p.Cid, p.Tid, p.Tids = data.Cid, data.Tid, data.Tids
	p.Team = ""
	p.Date = data.Date
	p.Rid = data.Rid
	p.Plate = ""
	p.Source = 8
	p.ServiceAddr = data.Address
	p.TireWorker = data.Operator
	p.Receipt = 0
	p.Pay = 0
	p.Cost = data.Cost
	p.ExtCost = 0.0
	p.Operator = data.Operator
	p.Uid = data.Uid
	p.Status = 0
	p.Remark = data.Remark
	woi := WorkOrderItemT{
		Cardid:  data.CardId,
		Sn:      data.Sn,
		Item:    6,
		Fault:   7,
		OldTno:  data.Tno,
		NewTno:  "",
		HasData: 0,
		Reason:  "",
		Pics:    data.Images,
	}
	p.Records = append(p.Records, woi)
}

type MaintainFixTireT struct {
	Cid      int      `bson:"cid"`
	Tid      string   `bson:"tid"`
	Tids     []string `bson:"tids"`
	Rid      string   `json:"rid" bson:"rid"`
	Vid      string   `json:"vid" bson:"vid"`
	CardId   int      `json:"cardid" bson:"cardid"`
	Sn       int      `json:"sn" bson:"sn"`
	Tno      string   `json:"tno" bson:"tno"`
	Type     int      `json:"type" bson:"type"`
	Cost     float64  `json:"cost" bson:"cost"`
	Remark   string   `json:"remark" bson:"remark"`
	Operator string   `json:"operator" bson:"operator"`
	Address  string   `json:"address" bson:"address"`
	Images   []string `json:"images" bson:"images"`
	T        int64    `json:"opt" bson:"t"`
	Date     int      `bson:"date"`
	Time     int      `bson:"time"`
	Uid      string   `bson:"-"`
}

// 提交补胎数据
func (p *HttpListener) MaintainFixTire(w http.ResponseWriter, req *http.Request) {
	if language, uid, ok := p.commonCheck(&w, req); ok {
		req.Header.Set("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept")
		w.Header().Add("Access-Control-Allow-Methods", "POST,GET,OPTIONS,DELETE")

		var sErr string
		var mft MaintainFixTireT

		//读取请求内容
		buf, err := p.readBody(req)
		if err == nil {
			err = json.Unmarshal(buf, &mft)
		}
		if err != nil {
			p.wrongParameter(&w, err, language)
			return
		}

		if mft.Rid != "" {
			mft.Cid, mft.Tids = p.dbo.getCompanyAndTeamByRid(mft.Rid)
		} else if mft.Vid != "" {
			mft.Cid, mft.Tids = p.dbo.getCompanyAndTeamByVid(mft.Vid)
		} else {
			p.wrongParameter(&w, errors.New("Rid/Vid不能同时为空"), language)
			return
		}
		lenTids := len(mft.Tids)
		if lenTids > 0 {
			mft.Tid = mft.Tids[lenTids-1]
		}

		mft.Uid = uid
		mft.Date, mft.Time = TimeToIntDateTime(time.Now())
		err = p.dbo.maintainFixtire(&mft)

		if err != nil {
			sErr = p.makeResultStr2(1032, "提交失败", err.Error(), language)
		} else {
			sErr = p.makeResultStr(0, "", language)
		}
		w.Write([]byte(sErr))
	}
}

// 轮胎修补列表
type MaintainFixTireListT struct {
	Oid      bson.ObjectId `bson:"_id" json:"-"`
	Id       string        `json:"id"`
	Cid      int           `bson:"cid" json:"-"`
	Tid      string        `bson:"tid" json:"-"`
	Team     string        `json:"team"`
	Rid      string        `json:"-" bson:"rid"`
	Vid      string        `json:"-" bson:"vid"`
	Plate    string        `json:"plate"`
	CardId   int           `bson:"cardid" json:"-"`
	Sn       int           `bson:"sn" json:"-"`
	Position string        `json:"sn"`
	Tno      string        `json:"tno" bson:"tno"`
	Type     int           `json:"type" bson:"type"`
	Cost     float64       `json:"cost" bson:"cost"`
	Operator string        `json:"operator" bson:"operator"`
	T        int64         `json:"opt" bson:"t"`
}

func (p *HttpListener) MaintainFixTireList(w http.ResponseWriter, req *http.Request) {
	if _, userid, ok := p.commonCheck(&w, req); ok {
		cid := req.FormValue("cid")
		tid := req.FormValue("tid")
		tno := req.FormValue("tno")
		sDate := req.FormValue("date")
		page := req.FormValue("page")

		var err error
		var iCid, iDate, iPage int

		iCid, err = strconv.Atoi(cid)
		if err != nil {
			iCid = 0
		}
		iPage, err = strconv.Atoi(page)
		if err != nil {
			iPage = 0
		}

		iDate, err = strconv.Atoi(sDate)
		if err != nil {
			iDate = 0
		}
		total, el := p.dbo.maintainFixTireList(userid, iCid, tid, tno, iDate, iPage)

		res := make(map[string]interface{})
		res["errcode"] = 0
		res["total"] = total
		res["datas"] = el

		var buf []byte
		buf, _ = json.Marshal(res)
		w.Write(buf)
	}
}

// 轮胎修改详情
type MaintainFixTireInfoT struct {
	Cid      int      `bson:"cid" json:"cid"`
	Tid      string   `bson:"tid" json:"tid"`
	Team     string   `json:"team"`
	Rid      string   `json:"rid" bson:"rid"`
	Vid      string   `json:"vid" bson:"vid"`
	Plate    string   `json:"plate"`
	CardId   int      `bson:"cardid" json:"-"`
	Sn       int      `bson:"sn" json:"-"`
	Position string   `json:"sn"`
	Tno      string   `json:"tno" bson:"tno"`
	Type     int      `json:"type" bson:"type"`
	Cost     float64  `json:"cost" bson:"cost"`
	Operator string   `json:"operator" bson:"operator"`
	T        int64    `json:"opt" bson:"t"`
	Remark   string   `bson:"remark" json:"remark"`
	Images   []string `bson:"images" json:"images"`
	Address  string   `bson:"address" json:"address"`
}

func (p *HttpListener) MaintainFixTireInfo(w http.ResponseWriter, req *http.Request) {
	if lang, _, ok := p.commonCheck(&w, req); ok {
		id := req.FormValue("id")

		if id == "" || !bson.IsObjectIdHex(id) {
			p.wrongParameter(&w, nil, lang)
			return
		}

		fti, err := p.dbo.maintainFixTireInfo(id)

		if err != nil {
			str := p.makeResultStr2(2000, "查询失败", err.Error(), lang)
			w.Write([]byte(str))
		} else {
			res := make(map[string]interface{})
			res["errcode"] = 0
			res["data"] = fti

			var buf []byte
			buf, _ = json.Marshal(res)
			w.Write(buf)
		}
	}
}

// 换胎数据结构
type MaintainExchangeTireT struct {
	Cid      int      `bson:"cid"`
	Tid      string   `bson:"tid"`
	Tids     []string `bson:"tids"`
	Uid      string   `bson:"uid"`
	Rid      string   `json:"rid" bson:"rid"`
	Vid      string   `json:"vid" bson:"vid"`
	Plate    string   `json:"plate" bson:"plate"`
	CardId   int      `json:"cardid" bson:"cardid"`
	Sn       int      `json:"sn" bson:"sn"`
	Tno      string   `json:"tno" bson:"tno"`
	Cost     float64  `json:"cost" bson:"cost"`
	Remark   string   `json:"remark" bson:"remark"`
	Operator string   `json:"operator" bson:"operator"`
	Address  string   `json:"address" bson:"address"`
	Images   []string `json:"images" bson:"images"`
	T        int64    `json:"opt" bson:"t"`
	Date     int      `bson:"date"`
	Time     int      `bson:"time"`
	Wid      int      `json:"wid" bson:"wid"`
	Status   int      `json:"status" bson:"status"`
	NewTire  struct {
		BrandId int    `json:"brandid" bson:"brandid"`
		Brand   string `json:"brand" bson:"brand"`
		Model   string `json:"model" bson:"model"`
		Pattern string `json:"pattern" bson:"pattern"`
		Depth   string `json:"depth" bson:"depth"`
		Tno     string `json:"tno" bson:"tno"`
		Dot     string `json:"dot" bson:"dot"`
		Rfid    string `json:"rfid" bson:"rfid"`
		Status  int    `json:"status" bson:"status"`
	}
}

// 提交换胎数据
func (p *HttpListener) MaintainExchangeTire(w http.ResponseWriter, req *http.Request) {
	if language, uid, ok := p.commonCheck(&w, req); ok {
		req.Header.Set("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept")
		w.Header().Add("Access-Control-Allow-Methods", "POST,GET,OPTIONS,DELETE")

		var sErr string
		var met MaintainExchangeTireT

		//读取请求内容
		buf, err := p.readBody(req)
		if err == nil {
			err = json.Unmarshal(buf, &met)
		}
		if err != nil {
			p.wrongParameter(&w, err, language)
			return
		}

		met.Uid = uid
		if met.Rid != "" {
			met.Cid, met.Tids = p.dbo.getCompanyAndTeamByRid(met.Rid)
		} else if met.Vid != "" {
			met.Cid, met.Tids = p.dbo.getCompanyAndTeamByVid(met.Vid)
		} else {
			p.wrongParameter(&w, errors.New("Rid/Vid不能同时为空"), language)
			return
		}
		lenTids := len(met.Tids)
		if lenTids > 0 {
			met.Tid = met.Tids[lenTids-1]
		}

		met.Date, met.Time = TimeToIntDateTime(time.Now())
		err = p.dbo.maintainExchangeTire(&met)

		if err != nil {
			sErr = p.makeResultStr2(1032, "提交失败", err.Error(), language)
		} else {
			sErr = p.makeResultStr(0, "", language)
		}
		w.Write([]byte(sErr))
	}
}

// 换胎列表
type MaintainExchangeTireListT struct {
	Oid      bson.ObjectId `bson:"_id" json:"-"`
	Id       string        `json:"id"`
	Cid      int           `bson:"cid" json:"-"`
	Tid      string        `bson:"tid" json:"-"`
	Team     string        `json:"team"`
	Plate    string        `json:"plate"`
	Tno      string        `json:"tno" bson:"tno"`
	CardId   int           `bson:"cardid" json:"-"`
	Sn       int           `bson:"sn" json:"-"`
	Position string        `json:"sn"`
	Cost     float64       `json:"cost" bson:"cost"`
	Operator string        `json:"operator" bson:"operator"`
	T        int64         `json:"opt" bson:"t"`
}

func (p *HttpListener) MaintainExchangeTireList(w http.ResponseWriter, req *http.Request) {
	if _, userid, ok := p.commonCheck(&w, req); ok {
		cid := req.FormValue("cid")
		tid := req.FormValue("tid")
		key := req.FormValue("key")
		sDate := req.FormValue("date")
		page := req.FormValue("page")

		var err error
		var iCid, iDate, iPage int

		iCid, err = strconv.Atoi(cid)
		if err != nil {
			iCid = 0
		}
		iPage, err = strconv.Atoi(page)
		if err != nil {
			iPage = 0
		}

		iDate, err = strconv.Atoi(sDate)
		if err != nil {
			iDate = 0
		}
		total, el := p.dbo.maintainExchangeTireList(userid, iCid, tid, key, iDate, iPage)

		res := make(map[string]interface{})
		res["errcode"] = 0
		res["total"] = total
		res["datas"] = el

		var buf []byte
		buf, _ = json.Marshal(res)
		w.Write(buf)
	}
}

// 换胎详情
type MaintainExchangeTireInfoT struct {
	Cid       int      `bson:"cid"`
	Tid       string   `bson:"tid"`
	Team      string   `bson:"team"`
	Rid       string   `bson:"rid" json:"rid"`
	Plate     string   `json:"plate" bson:"plate"`
	CardId    int      `json:"-" bson:"cardid"`
	Sn        int      `json:"-" bson:"sn"`
	Position  string   `json:"sn"`
	Tno       string   `json:"tno" bson:"tno"`
	Cost      float64  `json:"cost" bson:"cost"`
	Remark    string   `json:"remark" bson:"remark"`
	Operator  string   `json:"operator" bson:"operator"`
	Address   string   `json:"address" bson:"address"`
	Images    []string `json:"images" bson:"images"`
	T         int64    `json:"opt" bson:"t"`
	Wid       int      `json:"wid" bson:"wid"`
	Warehouse string   `json:"warehouse"`
	Status    int      `json:"status" bson:"status"`
	NewTire   struct {
		BrandId int    `json:"brandid" bson:"brandid"`
		Brand   string `json:"brand" bson:"brand"`
		Model   string `json:"model" bson:"model"`
		Pattern string `json:"pattern" bson:"pattern"`
		Depth   string `json:"depth" bson:"depth"`
		Tno     string `json:"tno" bson:"tno"`
		Dot     string `json:"dot" bson:"dot"`
		Rfid    string `json:"rfid" bson:"rfid"`
		Status  int    `json:"status" bson:"status"`
	}
}

func (p *HttpListener) MaintainExchangeTireInfo(w http.ResponseWriter, req *http.Request) {
	if lang, _, ok := p.commonCheck(&w, req); ok {
		id := req.FormValue("id")

		if id == "" || !bson.IsObjectIdHex(id) {
			p.wrongParameter(&w, nil, lang)
			return
		}

		fti, err := p.dbo.maintainExchangeTireInfo(id)

		if err != nil {
			str := p.makeResultStr2(2000, "查询失败", err.Error(), lang)
			w.Write([]byte(str))
		} else {
			buf := p.makeResultBuffer("data", fti)

			w.Write(buf)
		}
	}
}

// 换气门嘴数据结构
type MaintainFixValveT struct {
	Cid      int      `bson:"cid"`
	Tid      string   `bson:"tid"`
	Tids     []string `bson:"tids"`
	Uid      string   `bson:"uid"`
	Rid      string   `json:"rid" bson:"rid"`
	Vid      string   `json:"vid" bson:"vid"`
	Plate    string   `json:"plate" bson:"plate"`
	CardId   int      `json:"cardid" bson:"cardid"`
	Sn       int      `json:"sn" bson:"sn"`
	Tno      string   `json:"tno" bson:"tno"`
	Cost     float64  `json:"cost" bson:"cost"`
	Remark   string   `json:"remark" bson:"remark"`
	Operator string   `json:"operator" bson:"operator"`
	Address  string   `json:"address" bson:"address"`
	Images   []string `json:"images" bson:"images"`
	T        int64    `json:"opt" bson:"t"`
	Date     int      `bson:"date"`
	Time     int      `bson:"time"`
}

// 提交换气门嘴数据
func (p *HttpListener) MaintainFixValve(w http.ResponseWriter, req *http.Request) {
	if language, uid, ok := p.commonCheck(&w, req); ok {
		req.Header.Set("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept")
		w.Header().Add("Access-Control-Allow-Methods", "POST,GET,OPTIONS,DELETE")

		var sErr string
		var met MaintainFixValveT

		//读取请求内容
		buf, err := p.readBody(req)
		if err == nil {
			err = json.Unmarshal(buf, &met)
		}
		if err != nil {
			p.wrongParameter(&w, err, language)
			return
		}

		met.Uid = uid
		if met.Rid != "" {
			met.Cid, met.Tids = p.dbo.getCompanyAndTeamByRid(met.Rid)
		} else if met.Vid != "" {
			met.Cid, met.Tids = p.dbo.getCompanyAndTeamByVid(met.Vid)
		} else {
			p.wrongParameter(&w, errors.New("Rid/Vid不能同时为空"), language)
			return
		}
		lenTids := len(met.Tids)
		if lenTids > 0 {
			met.Tid = met.Tids[lenTids-1]
		}

		met.Date, met.Time = TimeToIntDateTime(time.Now())
		err = p.dbo.maintainFixValve(&met)

		if err != nil {
			sErr = p.makeResultStr2(1032, "提交失败", err.Error(), language)
		} else {
			sErr = p.makeResultStr(0, "", language)
		}
		w.Write([]byte(sErr))
	}
}

// 换气门嘴列表
type MaintainFixValveListT struct {
	Oid      bson.ObjectId `bson:"_id" json:"-"`
	Id       string        `json:"id"`
	Cid      int           `bson:"cid" json:"-"`
	Tid      string        `bson:"tid" json:"-"`
	Team     string        `json:"team"`
	Plate    string        `json:"plate"`
	Tno      string        `json:"tno" bson:"tno"`
	CardId   int           `bson:"cardid" json:"-"`
	Sn       int           `bson:"sn" json:"-"`
	Position string        `json:"sn"`
	Cost     float64       `json:"cost" bson:"cost"`
	Operator string        `json:"operator" bson:"operator"`
	T        int64         `json:"opt" bson:"t"`
}

func (p *HttpListener) MaintainFixValveList(w http.ResponseWriter, req *http.Request) {
	if _, userid, ok := p.commonCheck(&w, req); ok {
		cid := req.FormValue("cid")
		tid := req.FormValue("tid")
		key := req.FormValue("key")
		sDate := req.FormValue("date")
		page := req.FormValue("page")

		var err error
		var iCid, iDate, iPage int

		iCid, err = strconv.Atoi(cid)
		if err != nil {
			iCid = 0
		}
		iPage, err = strconv.Atoi(page)
		if err != nil {
			iPage = 0
		}

		iDate, err = strconv.Atoi(sDate)
		if err != nil {
			iDate = 0
		}
		total, el := p.dbo.maintainFixValveList(userid, iCid, tid, key, iDate, iPage)

		res := make(map[string]interface{})
		res["errcode"] = 0
		res["total"] = total
		res["datas"] = el

		var buf []byte
		buf, _ = json.Marshal(res)
		w.Write(buf)
	}
}

// 换气门嘴详情
type MaintainFixValveInfoT struct {
	Cid      int      `bson:"cid"`
	Tid      string   `bson:"tid"`
	Team     string   `bson:"team"`
	Rid      string   `bson:"rid" json:"rid"`
	Plate    string   `json:"plate" bson:"plate"`
	CardId   int      `json:"-" bson:"cardid"`
	Sn       int      `json:"-" bson:"sn"`
	Position string   `json:"sn"`
	Tno      string   `json:"tno" bson:"tno"`
	Cost     float64  `json:"cost" bson:"cost"`
	Remark   string   `json:"remark" bson:"remark"`
	Operator string   `json:"operator" bson:"operator"`
	Address  string   `json:"address" bson:"address"`
	Images   []string `json:"images" bson:"images"`
	T        int64    `json:"opt" bson:"t"`
}

func (p *HttpListener) MaintainFixValveInfo(w http.ResponseWriter, req *http.Request) {
	if lang, _, ok := p.commonCheck(&w, req); ok {
		id := req.FormValue("id")

		if id == "" || !bson.IsObjectIdHex(id) {
			p.wrongParameter(&w, nil, lang)
			return
		}

		fti, err := p.dbo.maintainFixValveInfo(id)

		if err != nil {
			str := p.makeResultStr2(2000, "查询失败", err.Error(), lang)
			w.Write([]byte(str))
		} else {
			buf := p.makeResultBuffer("data", fti)

			w.Write(buf)
		}
	}
}

// 加气数据结构
type MaintainInflateT struct {
	Cid      int      `bson:"cid"`
	Tid      string   `bson:"tid"`
	Tids     []string `bson:"tids"`
	Uid      string   `bson:"uid"`
	Rid      string   `json:"rid" bson:"rid"`
	Vid      string   `json:"vid" bson:"vid"`
	Plate    string   `json:"plate" bson:"plate"`
	CardId   int      `json:"cardid" bson:"cardid"`
	Sn       int      `json:"sn" bson:"sn"`
	Tno      string   `json:"tno" bson:"tno"`
	Cost     float64  `json:"cost" bson:"cost"`
	Remark   string   `json:"remark" bson:"remark"`
	Operator string   `json:"operator" bson:"operator"`
	Address  string   `json:"address" bson:"address"`
	Images   []string `json:"images" bson:"images"`
	T        int64    `json:"opt" bson:"t"`
	Date     int      `bson:"date"`
	Time     int      `bson:"time"`
}

// 提交加气数据
func (p *HttpListener) MaintainInflate(w http.ResponseWriter, req *http.Request) {
	if language, uid, ok := p.commonCheck(&w, req); ok {
		req.Header.Set("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept")
		w.Header().Add("Access-Control-Allow-Methods", "POST,GET,OPTIONS,DELETE")

		var sErr string
		var met MaintainInflateT

		//读取请求内容
		buf, err := p.readBody(req)
		if err == nil {
			err = json.Unmarshal(buf, &met)
		}
		if err != nil {
			p.wrongParameter(&w, err, language)
			return
		}

		met.Uid = uid
		if met.Rid != "" {
			met.Cid, met.Tids = p.dbo.getCompanyAndTeamByRid(met.Rid)
		} else if met.Vid != "" {
			met.Cid, met.Tids = p.dbo.getCompanyAndTeamByVid(met.Vid)
		} else {
			err = errors.New("Rid/Vid不能同时为空")
			p.wrongParameter(&w, err, language)
			return
		}
		lenTids := len(met.Tids)
		if lenTids > 0 {
			met.Tid = met.Tids[lenTids-1]
		}

		met.Date, met.Time = TimeToIntDateTime(time.Now())
		err = p.dbo.maintainInflate(&met)

		if err != nil {
			sErr = p.makeResultStr2(1032, "提交失败", err.Error(), language)
		} else {
			sErr = p.makeResultStr(0, "", language)
		}
		w.Write([]byte(sErr))
	}
}

// 加气列表
type MaintainInflateListT struct {
	Oid      bson.ObjectId `bson:"_id" json:"-"`
	Id       string        `json:"id"`
	Cid      int           `bson:"cid" json:"-"`
	Tid      string        `bson:"tid" json:"-"`
	Team     string        `json:"team"`
	Plate    string        `json:"plate"`
	Tno      string        `json:"tno" bson:"tno"`
	CardId   int           `bson:"cardid" json:"-"`
	Sn       int           `bson:"sn" json:"-"`
	Position string        `json:"sn"`
	Cost     float64       `json:"cost" bson:"cost"`
	Operator string        `json:"operator" bson:"operator"`
	T        int64         `json:"opt" bson:"t"`
}

func (p *HttpListener) MaintainInflateList(w http.ResponseWriter, req *http.Request) {
	if _, userid, ok := p.commonCheck(&w, req); ok {
		cid := req.FormValue("cid")
		tid := req.FormValue("tid")
		key := req.FormValue("key")
		sDate := req.FormValue("date")
		page := req.FormValue("page")

		var err error
		var iCid, iDate, iPage int

		iCid, err = strconv.Atoi(cid)
		if err != nil {
			iCid = 0
		}
		iPage, err = strconv.Atoi(page)
		if err != nil {
			iPage = 0
		}

		iDate, err = strconv.Atoi(sDate)
		if err != nil {
			iDate = 0
		}
		total, el := p.dbo.maintainInflateList(userid, iCid, tid, key, iDate, iPage)

		res := make(map[string]interface{})
		res["errcode"] = 0
		res["total"] = total
		res["datas"] = el

		var buf []byte
		buf, _ = json.Marshal(res)
		w.Write(buf)
	}
}

// 加气详情
type MaintainInflateInfoT struct {
	Cid      int      `bson:"cid"`
	Tid      string   `bson:"tid"`
	Team     string   `bson:"team"`
	Rid      string   `bson:"rid" json:"rid"`
	Plate    string   `json:"plate" bson:"plate"`
	CardId   int      `json:"-" bson:"cardid"`
	Sn       int      `json:"-" bson:"sn"`
	Position string   `json:"sn"`
	Tno      string   `json:"tno" bson:"tno"`
	Cost     float64  `json:"cost" bson:"cost"`
	Remark   string   `json:"remark" bson:"remark"`
	Operator string   `json:"operator" bson:"operator"`
	Address  string   `json:"address" bson:"address"`
	Images   []string `json:"images" bson:"images"`
	T        int64    `json:"opt" bson:"t"`
}

func (p *HttpListener) MaintainInflateInfo(w http.ResponseWriter, req *http.Request) {
	if lang, _, ok := p.commonCheck(&w, req); ok {
		id := req.FormValue("id")

		if id == "" || !bson.IsObjectIdHex(id) {
			p.wrongParameter(&w, nil, lang)
			return
		}

		fti, err := p.dbo.maintainInflateInfo(id)

		if err != nil {
			str := p.makeResultStr2(2000, "查询失败", err.Error(), lang)
			w.Write([]byte(str))
		} else {
			buf := p.makeResultBuffer("data", fti)

			w.Write(buf)
		}
	}
}

type ReportAccidentT struct {
	Oid      bson.ObjectId `bson:"_id" json:"oid"`
	User     string        `bson:"user" json:"user"`
	Plate    string        `json:"plate" bson:"plate"`
	Phone    string        `json:"phone" bson:"phone"`
	Remark   string        `json:"remark" bson:"remark"`
	NeedTire bool          `json:"needtire" bson:"needtire"`
	Address  string        `json:"address" bson:"address" `
	Images   []string      `json:"images" bson:"images"`

	Name     string `json:"name" bson:"name"`
	Cid      int    `json:"cid" bson:"cid"`
	Tid      string `json:"tid" bson:"tid"`
	TeamName string `json:"teamname" bson:"teamname"`
	Did      string `json:"did" bson:"did"`
	Date     int    `json:"date" bson:"date"`
	Time     int    `json:"time" bson:"time"`
	Status   int    `json:"status" bson:"status"`

	Progresses []OrderProgressT `json:"progresses" bson:"-"`
}

func (p *HttpListener) MaintainReportAccident(w http.ResponseWriter, req *http.Request) {
	if language, uid, ok := p.commonCheck(&w, req); ok {
		req.Header.Set("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept")
		w.Header().Add("Access-Control-Allow-Methods", "POST,GET,OPTIONS,DELETE")

		var sErr string
		var ra ReportAccidentT

		buf, err := p.readBody(req)
		if err == nil {
			err = json.Unmarshal(buf, &ra)
		}
		if err != nil {
			p.wrongParameter(&w, err, language)
			return
		}

		if ra.Address == "" || len(ra.Images) < 2 || ra.Phone == "" || ra.Plate == "" {
			p.wrongParameter(&w, errors.New("故障内容不完整"), language)
			return
		}

		ra.Date, ra.Time = TimeToIntDateTime(time.Now())
		ra.Oid = bson.NewObjectId()
		err = p.dbo.reportAccident(uid, &ra)

		if err != nil {
			sErr = p.makeResultStr2(1032, "提交失败", err.Error(), language)
		} else {
			sErr = p.makeResultStr(0, "", language)
		}
		w.Write([]byte(sErr))
	}
}

type ReportAccidentParamT struct {
	Cid  int    `json:"cid"`
	Tid  string `json:"tid"`
	Key  string `json:"key"`
	Date int    `json:"date"`
	Page int    `json:"page"`
}

type TotalReports struct {
	Total   int           `json:"total"`
	Reports []interface{} `json:"reports"`
}

func (p *HttpListener) MaintainReportAccidentList(w http.ResponseWriter, req *http.Request) {
	if language, userid, ok := p.commonCheck(&w, req); ok {
		req.Header.Set("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept")
		w.Header().Add("Access-Control-Allow-Methods", "POST,GET,OPTIONS,DELETE")

		var sErr string
		var param ReportAccidentParamT
		var ra []ReportAccidentT

		buf, err := p.readBody(req)
		if err == nil {
			err = json.Unmarshal(buf, &param)
		}
		if err == nil {
			if p.dbo.userType(userid) != UserTypeSystemUser && param.Cid == 0 {
				err = errors.New("无此权限")
			}
		}
		if err != nil {
			p.wrongParameter(&w, err, language)
			return
		}

		var count int
		count, ra, err = p.dbo.reportAccidentList(&param)
		for i := 0; i < len(ra); i++ {
			ra[i].Progresses, _ = p.dbo.maintainReportaccidentProgrss(ra[i].Oid.Hex())
		}

		if err != nil {
			sErr = p.makeResultStr2(2000, "查询失败", err.Error(), language)
			buf = []byte(sErr)
		} else {
			res := map[string]interface{}{
				"total":   count,
				"reports": ra,
			}

			buf = p.makeResultBuffer("data", res)
		}
		w.Write(buf)
	}
}

func (p *HttpListener) MaintainReportaccidentSetStatus(w http.ResponseWriter, req *http.Request) {
	if language, userId, ok := p.commonCheck(&w, req); ok {
		req.Header.Set("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept")
		w.Header().Add("Access-Control-Allow-Methods", "POST,GET,OPTIONS,DELETE")

		var sErr string
		var param OrderProgressT

		buf, err := p.readBody(req)
		if err == nil {
			err = json.Unmarshal(buf, &param)
		}
		if err == nil {
			if param.Oid == "" {
				err = errors.New("Oid不能为空")
			}
		}

		if err != nil {
			p.wrongParameter(&w, err, language)
			return
		}

		param.T = time.Now().Unix()
		param.User, param.Name = p.dbo.userId2UserInfo(userId)
		err = p.dbo.maintainReportaccidentSetStatus(&param)

		if err != nil {
			sErr = p.makeResultStr2(1101, "操作失败", err.Error(), language)

		} else {
			sErr = p.makeResultStr2(0, "", "", language)
		}
		w.Write([]byte(sErr))
	}
}

func (p *HttpListener) MaintainReportaccidentProgress(w http.ResponseWriter, req *http.Request) {
	if language, _, ok := p.commonCheck(&w, req); ok {
		req.Header.Set("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept")
		w.Header().Add("Access-Control-Allow-Methods", "POST,GET,OPTIONS,DELETE")

		var sErr string
		var param struct {
			Oid string `json:"oid"`
		}
		var res []OrderProgressT

		buf, err := p.readBody(req)
		if err == nil {
			err = json.Unmarshal(buf, &param)
		}
		if err == nil {
			if param.Oid == "" {
				err = errors.New("Oid不能为空")
			}
		}

		if err != nil {
			p.wrongParameter(&w, err, language)
			return
		}

		res, err = p.dbo.maintainReportaccidentProgrss(param.Oid)

		if err != nil {
			sErr = p.makeResultStr2(2000, "查询失败", err.Error(), language)
			buf = []byte(sErr)
		} else {

			buf = p.makeResultBuffer("data", res)
		}
		w.Write(buf)
	}
}

const LOCALHOST string = "127.0.0.1:"
const LOCALHOSTLEN int = 10

func (p *HttpListener) commonCheck(w *http.ResponseWriter, req *http.Request) (language string, userid string, result bool) {
	(*w).Header().Add("Access-Control-Allow-Origin", "*")

	query := req.URL.Query()
	language = query.Get("lang")
	if language == "" {
		language = "cn"
	}

	//检查userid/accesstoken
	userid = query.Get("userid")
	accesstoken := query.Get("accesstoken")

	if userid == "" && accesstoken == "" {
		//如果是本地IP，则无需判断用户
		rip := req.RemoteAddr
		if len(rip) > LOCALHOSTLEN && rip[:LOCALHOSTLEN] == LOCALHOST {
			return "cn", "", true
		}

		s := p.makeResultStr(1003, "缺少必要的字段", language)
		(*w).Write([]byte(s))
		result = false
		return
	}

	//if !p._ac.Check(userid, accesstoken) {
	//	s := p.makeResultStr(1006, "非法访问", language)
	//	(*w).Write([]byte(s))
	//	result = false
	//	return
	//}

	//检查accesstoken是否正确
	if !bson.IsObjectIdHex(userid) || !p.dbo.checkAccessToken(userid, accesstoken) {
		s := p.makeResultStr(1006, "非法访问", language)
		(*w).Write([]byte(s))
		result = false
		return
	}

	if req.Method != "POST" {
		s := p.makeResultStr(1002, "无效的访问方式", language)
		(*w).Write([]byte(s))
		result = false
		return
	}
	result = true

	return
}

// 检查字段是否为空
func (p *HttpListener) checkFields(w *http.ResponseWriter, language string, fields ...string) bool {
	for _, field := range fields {
		if field == "" {
			s := p.makeResultStr(1003, "缺少必要的字段", language)
			(*w).Write([]byte(s))
			return false
		}
	}
	return true
}

// 参数错误处理函数
func (p *HttpListener) wrongParameter(w *http.ResponseWriter, err error, lang string) {
	sErr := "参数错误"

	if err == nil {
		sErr = p.makeResultStr(1009, sErr, lang)
	} else {
		sErr = p.makeResultStr2(1009, sErr, err.Error(), lang)
	}

	(*w).Write([]byte(sErr))
}

func (p *HttpListener) makeResultStr(code int, msg string, lang string) string {
	if code == 0 {
		if msg != "" {
			return fmt.Sprintf(`{"errcode":0, %s}`, msg)
		} else {
			return `{"errcode":0}`
		}
	} else {
		newmsg := p.langSwitcher.Get(code, lang)
		if newmsg == "" {
			newmsg = msg
		}
		return fmt.Sprintf(`{"errcode":%d,"msg":"%s"}`, code, newmsg)
	}
}

func (p *HttpListener) makeResultStr2(code int, msg, extMsg string, lang string) string {
	if code == 0 {
		if msg != "" {
			return fmt.Sprintf(`{"errcode":0, %s}`, msg)
		} else {
			return `{"errcode":0}`
		}
	} else {
		newmsg := p.langSwitcher.Get(code, lang)
		if newmsg == "" {
			newmsg = msg
		}
		return fmt.Sprintf(`{"errcode":%d,"msg":"%s:%s"}`, code, newmsg, extMsg)
	}
}

func (p *HttpListener) makeResultBuffer(key string, data interface{}) []byte {
	inf := map[string]interface{}{"errcode": 0, key: data}
	buf, _ := json.Marshal(inf)

	return buf
}

func (p *HttpListener) makeResultRedirect(url string) []byte {
	inf := map[string]interface{}{"errcode": 302, "url": url}
	buf, _ := json.Marshal(inf)

	return buf
}

func (p *HttpListener) readBody(req *http.Request) ([]byte, error) {
	buf, err := ioutil.ReadAll(req.Body)
	defer req.Body.Close()

	if err != nil {
		return nil, err
	}

	return buf, nil
}

// 发送数据
func (p *HttpListener) Post(url string, contentType string, buf []byte) ([]byte, error) {
	resp, err := http.Post(url, contentType, bytes.NewReader(buf))
	if err != nil {
		return nil, err
	}

	defer resp.Body.Close()
	body, _ := ioutil.ReadAll(resp.Body)
	return body, nil
}

func (p *HttpListener) CheckAccess(user, token string) bool {
	param := map[string]string{
		"userid":      user,
		"accesstoken": token,
	}
	buf, _ := json.Marshal(param)
	var err error
	buf, err = p.Post(p.cfg.CheckAccessURL+"/checkaccess", "", buf)

	if err != nil {
		return false
	} else {
		var result struct {
			ErrCode int `json:"errcode"`
		}
		err = json.Unmarshal(buf, &result)
		if err != nil {
			return false
		}
		return result.ErrCode == 0
	}
}

type CustomSoundT struct {
	FrameId int    `json:"frame_id"`
	Text    string `json:"sound_text"`
}
type CallT struct {
	TaskUuid    string         `json:"task_uuid"`
	Phone       string         `json:"called_num"`
	OrderTime   string         `json:"order_time"`
	CustomSound []CustomSoundT `json:"cust_sound"`
}

// 拨打电话的结果
type CallResultT struct {
	Code  string `json:"code"`
	Error string `json:"error"`
}

func (p *HttpListener) makeCall(phone, text string) error {
	call := CallT{TaskUuid: p.cfg.AlertCall.TaskUuid, Phone: phone, OrderTime: time.Now().Format("2006-01-02 15:04:05"),
		CustomSound: make([]CustomSoundT, 0)}
	cs := CustomSoundT{FrameId: p.cfg.AlertCall.FrameId, Text: text}
	call.CustomSound = append(call.CustomSound, cs)

	buf, _ := json.Marshal(call)

	res, err := p.Post(p.cfg.AlertCall.Host, "application/json", buf)

	if err != nil {
		return err
	}

	var callRes CallResultT
	err = json.Unmarshal(res, &callRes)
	if err != nil {
		return err
	}

	if callRes.Code != "200" {
		msg := callRes.Error
		if msg == "" {
			msg = "错误代码为" + callRes.Code
		}
		return errors.New(msg)
	}

	return nil
}

// 判断用户类型
func (p *HttpListener) checkCustomerType(ut string) (userType int, err error) {
	userType, err = strconv.Atoi(ut)
	if err != nil {
		return
	}

	var userTypes []int = []int{0, 1, 2, 3, 4, 5, 6, 7, 100}
	for _, v := range userTypes {
		if v == userType {
			return v, nil
		}
	}

	return 0, errors.New("invalid user type")
}

// 判断设备/车辆类型
func (p *HttpListener) checkVehicleType(vt string) (vehicleType int, err error) {
	vehicleType, err = strconv.Atoi(vt)
	if err != nil {
		return
	}

	var vehicleTypes []int = []int{1, 2, 3, 4, 5, 6, 101, 102, 103, 104, 105, 201, 202,
		301, 302, 303, 304, 305}
	for _, v := range vehicleTypes {
		if v == vehicleType {
			return v, nil
		}
	}

	return 0, errors.New("invalid veicle type")
}
